Skip to content

Python class method(self)

  • by

In Python programming, self is used in instance methods, cls is often used in class methods.

cls is generally used in the __new__ special staticmethod, or in classmethods, which you make similarly to staticmethods. These are methods that only need access to the class, but not to things specific to each instance of the class.

Python class method(self) example

Simple example code.

Note: self, cls is just a convention, and you could call it whatever you wanted.

class C:
    @classmethod
    def f(cls):
        print(cls.__name__, type(cls))


C.f()

Output:

Python class method(self)

Another example

class App:
    price = 120

    def display(self):
        print('The price is:', self.price)


# create display class method
App.printPrice = classmethod(App.display)

App().display()

Output: The price is: 120

Do comment if you have any doubts any suggestions on this Python method topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *