The Python cls
Parameter
The cls
parameter is used in a class
method to gain access to the class to which the method belongs.
class MyClass: classVariable = 10 # a class method @classmethod def myMethod(cls): return cls.classVariable MyClass.myMethod() # Call the class method
Here, myMethod
has cls
as a parameter. When we call the class
method myMethod
, Python will pass the method's class as a paraneter to that
method via the cls
parameter. It's like calling
MyClass.myMethod(MyClass)
but we don't actually pass
MyClass
in. Python does it for us, and does it silently.
cls
means "the class to which this method belongs", or "this" class. It's
simliar to how the self
parameter works.
Note
The name "cls" is just a convention. The first parameter of a class method will always be a
reference to the class to which the method belongs, and by convention we use "cls". You're
welcome to call it "thisClass" or whatever you fancy. You cannot call it class
,
though, since that's a reserved word. To make life easier for others it's best to stick to
conventions and use "cls".