cls()函数在类方法中做什么? [英] What does cls() function do inside a class method?

查看:264
本文介绍了cls()函数在类方法中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我正在查看他人的代码,并看到了以下内容:

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

cls()函数在这里做什么?

如果我得到了其他一些类继承此 A 类,将其称为 C ,在调用此get方法时,该 o 使用 C 类作为 cls()的调用者?

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

推荐答案

对于 classmethod s,第一个参数是通过其使用class方法的类被调用,而不是通常的 self 来调用 instancemethod s(除非另有说明,否则类中的所有方法都是隐式的)

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).

下面是一个例子- -为了便于练习,我添加了一个例外检查 cls 参数的身份。

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 <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 :(

这篇关于cls()函数在类方法中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆