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()
?
It's a class factory.
Essentially it the same as calling:
cls
indef get(...):
isA
.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.
For
classmethod
s, the first parameter is the class through which the class method is invoked with instead of the usualself
forinstancemethod
s (which all methods in a class implicitly are unless specified otherwise).Here's an example -- and for the sake of exercise, I added an exception that checks the identity of the
cls
parameter.