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

前端 未结 3 1799
一生所求
一生所求 2021-02-01 22:26

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         


        
3条回答
  •  盖世英雄少女心
    2021-02-01 23:07

    For classmethods, the first parameter is the class through which the class method is invoked with instead of the usual self for instancemethods (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.

    class Base(object):
        @classmethod
        def acquire(cls, param):
            if cls is Base:
                raise Exception("Must be called via subclass :(")
            return "this is the result of `acquire`ing a %r with %r" % (cls, param)
    
    class Something(Base):
        pass
    
    class AnotherThing(Base):
        pass
    
    print Something.acquire("example")
    print AnotherThing.acquire("another example")
    print Base.acquire("this will crash")
    

    this is the result of `acquire`ing a  with 'example'
    this is the result of `acquire`ing a  with 'another example'
    Traceback (most recent call last):
      File "classmethod.py", line 16, in 
        print Base.acquire("this will crash")
      File "classmethod.py", line 5, in acquire
        raise Exception("Must be called via subclass :(")
    Exception: Must be called via subclass :(
    

提交回复
热议问题