DEV Community

Vera-778
Vera-778

Posted on

Instance Attributes & Class Attributes

class Square:
    def __init__(self, side):
        self.side = side
    def area(self): # self parameter - this is an instance method
        return self.side ** 2
    def calculate_area(side): # No self parameter - this is a class method 
        return side ** 2

sq = Square(10) # Create an instance
print(sq.area()) # Invoke an instance method
print(Square.calculate_area(20)) # Invoke a class method
Enter fullscreen mode Exit fullscreen mode

The method can be invoked by using the class name and the method name. It provides a way of organising methods that are related to the class, but do not belong on the instances themselves.

If the attribute is a field then you can make it a class field by defining it outside the constructor. It will be then shared by all class instances. it represents a characteristic of the entire class rather than individual objects. Class fields have a single value shared by all instances. Hence changing the value impacts all instances equally as shown in the example below:

class Square:
    nbInstances = 0
    def __init__(self, side):
        self.side = side
        Square.nbInstances += 1
    def area(self): # self parameter - this is an instance method
        return self.side ** 2
    def calculate_area(side): # No self parameter - this is a class method 
        return side ** 2

sq = Square(10) # Create an instance
print(sq.area()) # Invoke an instance method
print(Square.calculate_area(20)) # Invoke a class method
print(Square.nbInstances) # Outputs 1
print(sq.nbInstances) # Outputs 1
sq2 = Square(10) # Create another instance
print(Square.nbInstances) # Outputs 2
print(sq.nbInstances) # Outputs 2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)