Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does cls() function do inside a class method?

Tags:

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()?

like image 860
Zen Avatar asked Jul 17 '14 09:07

Zen


People also ask

What does CLS stand for Python?

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.

Is CLS the same as self?

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.

How do you create a method inside a class in Python?

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.


1 Answers

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.

like image 135
RvdK Avatar answered Sep 19 '22 16:09

RvdK