cls()函数在类方法中做了什么?

Zen*_*Zen 10 python class

今天我正在查看另一个代码,看到了这个:

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
Run Code Online (Sandbox Code Playgroud)

这个cls()功能在这做什么?

如果我让其他类继承这个A类,调用它C,在调用这个get方法时,这会o使用Cclass作为调用者cls()吗?

Rvd*_*vdK 16

cls是构造函数,它将构造类A并调用该__init__(self, uid=None)函数.

如果你使用它(使用C),cls将保持'C',(而不是A),请参阅AKX答案.


AKX*_*AKX 9

对于classmethods,第一个参数是通过其调用类方法而不是通常self用于instancemethods的类(除非另有说明,否则隐式使用类中的所有方法).

这是一个例子 - 为了练习,我添加了一个检查cls参数身份的异常.

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")
Run Code Online (Sandbox Code Playgroud)
this is the result of `acquire`ing a <class '__main__.Something'> with 'example'
this is the result of `acquire`ing a <class '__main__.AnotherThing'> with 'another example'
Traceback (most recent call last):
  File "classmethod.py", line 16, in <module>
    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 :(
Run Code Online (Sandbox Code Playgroud)

  • 这并没有真正回答OP关于`cls()``在他看过的类方法中做了什么的问题.正如我所说(@classmethods除外)它是一个工厂. (7认同)
  • +1,我总是喜欢显示它的实际代码! (4认同)

Jam*_*lls 7

这是一个班级工厂.

基本上它与调用相同:

o = A(uid)
Run Code Online (Sandbox Code Playgroud)

clsdef get(...): A.

  • 随意建议改进编辑.这是一个社区论坛. (4认同)
  • 这个答案里有大量的预期知识。 (3认同)