[英]How to get class when I can't use self - Python
I have one weird problem. 我有一个奇怪的问题。 I have following code:
我有以下代码:
class A:
def f():
return __class__()
class B(A):
pass
a = A.f()
b = B.f()
print(a, b)
And output is something like this: 输出是这样的:
<__main__.A object at 0x01AF2630> <__main__.A object at 0x01B09B70>
So how can I get B
instead of second A
? 所以,我怎么能得到
B
代替第二的A
?
The magic __class__
closure is set for the method context and only really meant for use by super()
. 为方法上下文设置了神奇的
__class__
闭包 ,只是真正意味着由super()
。
For methods you'd want to use self.__class__
instead: 对于你想要使用
self.__class__
:
return self.__class__()
or better still, use type(self)
: 或者更好的是,使用
type(self)
:
return type(self)()
If you want to be able to call the method on a class, then use the classmethod
decorator to be handed a reference to the class object, rather than remain unbound: 如果您希望能够在类上调用该方法,那么使用
classmethod
装饰器来传递对类对象的引用,而不是保持未绑定:
@classmethod
def f(cls):
return cls()
classmethod
s are always bound to the class they are called on, so for Af()
that'd be A
, for Bf()
you get handed in B
. classmethod
s总是绑定到它们被调用的类,所以对于Af()
,它是A
,对于Bf()
你得到了B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.