Python cls() 函数在类方法中做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24799403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does cls() function do inside a class method?
提问by Zen
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?
这个cls()函数在这里做什么?
If I got some other classes inherit this Aclass, call it C, when calling this get method, would this ouse Cclass as the caller of cls()?
如果我让其他一些类继承了这个A类,调用它C,当调用这个get方法时,它会o使用C类作为调用者cls()吗?
采纳答案by AKX
For classmethods, the first parameter is the class through which the class method is invoked with instead of the usual selffor instancemethods (which all methods in a class implicitly are unless specified otherwise).
对于classmethods,第一个参数是通过其调用类方法的类,而不是通常的selffor instancemethods(除非另有说明,否则类中的所有方法都是隐式的)。
Here's an example -- and for the sake of exercise, I added an exception that checks the identity of the clsparameter.
这是一个示例——为了练习起见,我添加了一个检查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")
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 :(
回答by James Mills
It's a class factory.
这是一个班级工厂。
Essentially it the same as calling:
本质上它与调用相同:
o = A(uid)
clsin def get(...):isA.
cls在def get(...):是A。
回答by RvdK
clsis the constructor function, it will construct class A and call the __init__(self, uid=None)function.
cls是构造函数,它将构造类A并调用该__init__(self, uid=None)函数。
If you enherit it (with C), the cls will hold 'C', (and not A), see AKX answer.
如果您继承它(使用 C),cls 将保留“C”(而不是 A),请参阅 AKX 答案。

