Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)
I was going through PEP 0008 Style Guide, and I came across a statement suggesting that using the self as the first argument is an instance function, but if cls is used as the first parameter then it will be a class method.

I am not familiar with the class method, kindly share some codes for the same.

1 Answer

0 votes
by (107k points)

Let me first explain class methods:

When the class method is called, it takes a cls argument to the class instance, not the object instance. This is because the class method only has access to this cls argument, it can’t modify the object instance state. That would require access to self. However, class methods can still modify the class state that applies across all instances of the class. Kindly refer to the example below that defines a class method. You need to use the class method with the class itself. In this instance, the class method is using the class property name variable.

class Car:

    name = 'Ferrari'

    @classmethod

    def printNamefunction(cls):

        print('The name is:', cls.name)

Car.printNamefunction()

You can also work with a classmethod with both objects and the class like:

car1= Car()

car2= Car()

Car.printName()

car1.printName()

car2.printName()

The argument 'name' is now belongs to the class which means now if you tried to change the name by using an object, it will then ignores that call. But if you do the same thing with the class, it will change. Refer the below example:

car1.name="Lamborghini"

Car.printName()

car1.printName()

car2.printName()

Car.name="Lamborghini"

Car.printName()

car1.printName()

car2.printName()

 If you are newbie and want to explore more about Python, then learn python from the below video tutorial:

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...