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 classmethod
s, which you make similarly to staticmethod
s. 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:
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.