Classes and Objects

What's Class

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.

Class Syntax

  • Classes are created by keyword class

  • Attributes are the variables that belong to a class

  • Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute

class ClassName:
    Statement

Car Example 😂

class Car: 
    # attributes
    color = "red"
    body = "sedan"
    
    # methods
    def specs(self):
        print("car color is", self.color)
        print("body type is", self.body)


# Object instantiation
Bmw = Car()

# Accessing class attributes
# and method through objects
print(Bmw.color)
Bmw.specs()


Output:
red
car color is red
body type is sedan

The Self

  • The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

  • Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it.

  • If we have a method that takes no arguments, then we still have to have one argument.

__init__ Method

it's similar to constructors in C++ and Java

Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.

Class and Instance Variables

Instance variables are for data, unique to each instance and class variables are for attributes and methods shared by all instances of the class. Instance variables are variables whose value is assigned inside a constructor or method with self whereas class variables are variables whose value is assigned in the class.

Modify Object Properties

You can modify properties on objects like this:

Delete Object Properties

You can delete properties on objects by using the del keyword:

Delete Objects

You can delete objects by using the del keyword:

The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

Last updated