Python class method

Class method:

The class method in python class is achieved by using built-in decorator called @classmethod or classmethod()

 - > By using class method we can call the class method with or without creating an object
 -  > Addition to that we can access all the properties of the class

Which means that class method is bound to a class rather than the objects of that class.

Since creating object is not necessary in class method we no need to include self as parameter in methods.

However to access all the properties of class we need to include 'cls' as parameter 

Note: As self is the reference of object 

Using @classmethod in class:
class Car:

brand = 'Rolls-Royce'
fast = 155

@classmethod # create speed class method
def speed(cls):

print(cls.brand + ' speeds ', cls.fast, 'mph')

Car.speed() # with out creating object calling the method

obj = Car() # creating object
obj.speed() # calling the method

Output:


Using classmethod() in class:
class Car:

brand = 'Rolls-Royce'
fast = 155

def speed(cls):

print(cls.brand + ' speeds ', cls.fast, 'mph')

Car.speed =classmethod(Car.speed) # create speed class method
Car.speed() # with out creating object calling the method

obj = Car() # creating object
obj.speed() # calling the method

Output:


Comments

Popular posts from this blog

Switch frame in selenium python

Learn basics of python collection data type (list, tuple, dictionary and set) instantly

Python property method