We read about classes and objects in the previous chapter. We also read that the attributes which belong to a class and are accessible by all the objects of the class are called class attributes and the attributes which belong to objects are called instance attributes. In this chapter, we will be looking at different types of methods a class can have.
Till now, the methods we have seen were used to access or change instance attributes. These are called instance methods and you will be using mostly these methods only in classes.
However, there are two other types of methods: class methods and static methods. Class methods are used to access or change class attributes. Static methods are normal functions which don’t deal with anything related to classes. For example, static methods can be used to print some message or detect if a number passed to it is even.
Let’s look at them one by one.
Python Instance Methods
Instance methods are the regular methods we use in classes. These are used most of the time. Till now, all the methods we saw were instance methods.
We know that instance methods take self
as the first parameter which refers to an object of the class. These are mostly used to access or change the attributes of the object on which they are called.
Instance methods can be called only by the objects of the class in which they are defined.
class Student():
def __init__(self, name):
self.name = name
def display(self):
return self.name
st1 = Student("John")
st2 = Student("Johny")
print(st1.display())
print(st2.display())
The display()
method is an instance method and so it receives self
as a parameter which refers to the current object (object which calls the method). It accesses the attribute name
in self.name
of only the object which calls this method.
When the object st1
calls the method, then self.name
becomes the same as st1.name
. When st2
calls the method, then self.name
becomes the same as st2.name
.
Python Class Methods
Class methods take cls
as the first parameter which refers to the current class. These are used to access or change the class attributes. You know that class attributes can be accessed by all the objects of a class.
To define a class method, @classmethod
decorator is used before the function definition. We will read more about decorators later.
Class methods can be called by the objects of the class as well as by the class in which they are defined. So unlike instance methods, we can call class methods directly with class (without making any object).
class Student():
name = "John"
@classmethod
def create(cls):
return cls.name
print(Student.create())
In this example, create()
is a class method because it is defined following the @classmethod
decorator. This method is called by the Student
class by writing Student.create()
and so it takes the class Student
as its first parameter cls
.
It accesses the class attribute name
by writing cls.name
. Writing cls.name
is the same as writing Student.name
.
Let’s look at another example in which a class method is used to call the constructor when an object of the class is created.
class Student():
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def create(cls, name, age):
return cls(name, age + 1)
st1 = Student("John", 20)
st2 = Student.create("Johny", 30)
print(st1.age)
print(st2.age)
In this example, the first object st1
is created normally using constructor and the second object st2
is created using the create()
class method.
In the create method, return cls(name, age + 1) is similar to return Student(name, age + 1).
The create()
method takes the Student
class as its first parameter cls
, and name
and age
as the other two parameters. Then it increases the age by 1 and finally returns the constructor by calling cls(name, age + 1)
(Writing cls(name, age + 1)
is the same as writing Student(name, age + 1)
) .This returned constructor creates a new instance with the passed name and age.
Python Static Methods
Static methods, like class methods, are bound to a class and not its objects. A static method doesn’t know anything about the attributes or other definitions of the class in which it is defined. These are mostly used as independent utility functions which don’t access or interfere with the state or attributes of the class.
To define a static method, @staticmethod
decorator is used before the function definition.
Static methods can be called by the objects of the class as well as by the class itself in which they are defined.
class Number():
@staticmethod
def even(x):
if x % 2 == 0:
return True
else:
return False
print(Number.even(40))
In this example, even()
is a static method because it is defined following the @staticmethod
decorator. And yes, as we said, it is just a normal function defined inside a class and doesn’t interfere with the class members. It returns True if its parameter is even, and returns False otherwise.
Let’s see an example where class method and static method are used together.
class Person():
def __init__(self, name, age, can_vote):
self.name = name
self.age = age
self.can_vote = can_vote
@staticmethod
def is_adult(age):
if age >= 18:
return True
else:
return False
@classmethod
def create(cls, name, age):
if cls.is_adult(age) == True:
return cls(name, age, "Yes")
else:
return cls(name, age, "No")
st1 = Person.create("John", 15)
st2 = Person.create("Johny", 20)
print("Can", st1.name, "vote?", st1.can_vote)
print("Can", st2.name, "vote?", st2.can_vote)
In the above example, is_adult()
is a static method which returns True if the age passed to it is greater than or equal to 18, and returns False otherwise.
create()
is a class method which calls the constructor with suitable arguments.
st1 = Person.create("John", 15)
- While creating an object st1
, the Person
class calls the create()
method passing the name
and age
parameters.
The create()
method internally calls the is_adult()
method which returns True or False depending on whether the age passed to it is greater than 18 or not. If it returns True, then the create()
method calls the constructor with the third argument as “Yes”, otherwise calls it with the third argument as “No”. The constructor then assigns the passed values to the name
, age
and can_vote
attributes of the current object st1
.
Similarly, the other object st2
is created.
We read about the three types of methods we can deal with in OOP, but mostly we use instance methods.