Introduction
Methods help organize code inside classes. Different method types serve different jobs to keep code clear and easy to use.
Jump into concepts and practice - no test required
Methods help organize code inside classes. Different method types serve different jobs to keep code clear and easy to use.
class ClassName: def instance_method(self, args): # works with object data pass @classmethod def class_method(cls, args): # works with class data pass @staticmethod def static_method(args): # independent function inside class pass
self refers to the object calling the method.
cls refers to the class itself, not an object.
bark uses object data name.class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says Woof!")
get_species accesses shared class data species.class Dog: species = "Canis familiaris" @classmethod def get_species(cls): return cls.species
is_dog checks something related but does not use object or class data.class Dog: @staticmethod def is_dog(animal): return animal.lower() == "dog"
This program shows all three method types working together in a class.
class Car: wheels = 4 # class attribute def __init__(self, color): self.color = color # instance attribute def paint(self, new_color): self.color = new_color # instance method changes object data @classmethod def number_of_wheels(cls): return cls.wheels # class method returns shared data @staticmethod def honk(): print("Beep beep!") # static method unrelated to object or class data car1 = Car("red") print(car1.color) # red car1.paint("blue") print(car1.color) # blue print(Car.number_of_wheels()) # 4 Car.honk()
Instance methods always need self to access object data.
Class methods use cls to access or change class-wide data.
Static methods are like normal functions but kept inside the class for organization.
Instance methods work with data unique to each object.
Class methods work with data shared by all objects of the class.
Static methods perform tasks related to the class but don't use object or class data.
class Example:
count = 0
def __init__(self):
Example.count += 1
@classmethod
def get_count(cls):
return cls.count
obj1 = Example()
obj2 = Example()
print(Example.get_count())class Calculator:
@staticmethod
def add(x, y):
return x + y
@classmethod
def multiply(cls, x, y):
return x * y
print(Calculator.add(2, 3))
print(Calculator.multiply(2, 3))