NEXT TUTORIAL >> Inheritance in Python
Class variables are the variables whose single copy is shared to all the instances of a class. Class variables are also known as static variables in Python.
To understand this, consider ‘n’ is an class variable and if we create 2 two instances, then, there will be only single copy for variable ‘n’.
If we modify copy of ‘n’ in any of two instance, then, it will modify other one as well.
Let’s see one example,
class Test:
count = 1
@classmethod
def modify(cls):
cls.count += 1
# creating 2 instances of our class Test
i1 = Test()
i2 = Test()
print('count for i1 : ', i1.count)
print('count for i2 : ', i2.count)
print('modifying count for i2')
i2.modify()
print('count for i1 now: ', i1.count)
print('count for i2 now: ', i2.count)
O/P
count for i1 : 1
count for i2 : 1
modifying count for i2
count for i1 now: 2
count for i2 now: 2
In the above code, we created two copies for variable count, and upon modifying one copy, other one was also modified.
To mark any method inside a class as a class method, we should use built-in decorator @classmethod.
Learn more about decorators here : http://codeofgeeks.com/function-decorator-in-python-with-examples/
A class method contains ‘cls’ as the first parameter with the help of which we can access the class variables.
To access the class variables from outside the class, we can use
classname.variable # Example : Main.n
Class methods
Class methods are the methods that act on class level. Class methods are written using @classmethod decorator.
Let’s try to create a Student database using Instance methods and variables,
class Student:
college = 'IIT' # class variable
@classmethod
def getStudent(cls, name, rollno, marks):
print('\nDetails provided')
print('Name: ', name)
print('Roll Number: ', rollno)
print('Marks: ', marks)
print('College: ', cls.college)
Student.getStudent('Krishna', 124, '100%')
O/P
Details provided
Name: Krishna
Roll Number: 124
Marks: 100%
College: IIT
That’s all here.
NEXT TUTORIAL >> Inheritance in Python
