Today I'm viewing another's code, and saw this:
class A(B):
# Omitted bulk of irrelevant code in the class
def __init__(self, uid=None):
self.uid = str(uid)
@classmethod
def get(cls, uid):
o = cls(uid)
# Also Omitted lots of code here
what does this cls()
function do here?
If I got some other classes inherit this A
class, call it C
, when calling this get method, would this o
use C
class as the caller of cls()
?
cls refers to the class, whereas self refers to the instance. Using the cls keyword, we can only access the members of the class, whereas using the self keyword, we can access both the instance variables and the class attributes. With cls, we cannot access the instance variables in a class.
self vs clsThe difference between the keywords self and cls reside only in the method type. If the created method is an instance method then the reserved word self has to be used, but if the method is a class method then the keyword cls must be used.
To make a method as class method, add @classmethod decorator before the method definition, and add cls as the first parameter to the method. The @classmethod decorator is a built-in function decorator. In Python, we use the @classmethod decorator to declare a method as a class method.
cls
is the constructor function, it will construct class A and call the __init__(self, uid=None)
function.
If you enherit it (with C), the cls will hold 'C', (and not A), see AKX answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With