The attributes are the variables that store the data of an object, and the methods are the functions that define what the object can do.
Instance attributes
They belong to each object and are usually created in __init__ using self:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
r = Rectangle(4, 3)
print(r.width) # 4
r.width = 10 # attributes can be modified
Class attributes
They are defined inside the class and are shared by all its objects:
class Circle:
PI = 3.14159 # class attribute
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.PI * self.radius ** 2
print(Circle(2).area()) # 12.56636
Instance methods
They receive the object as the first parameter (self) and can read and change its attributes:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def scale(self, factor):
self.width *= factor
self.height *= factor
r = Rectangle(4, 3)
r.scale(2)
print(r.area()) # 48
Class methods and static methods
@classmethodreceives the class (cls) instead of the object. It is often used as an alternative constructor.@staticmethoddoes not receive the object or the class. It is a normal function placed inside the class because it is related to it.
class Temperature:
@staticmethod
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
print(Temperature.celsius_to_fahrenheit(100)) # 212.0
Adding attributes dynamically
Python allows you to create new attributes on an object at any moment (r.color = "red"), but it is a better practice to define all of them in __init__.