[英]I want to get the class of a subclass
Can I, in a class that is meant to be subclassed, get the class variable for an instance of its children? 我是否可以在要进行子类化的类中获取其子实例的类变量? Something like this: 像这样:
class A:
...
def doStuff(self):
c = getChildClass(self)
setattr(c, 'anAttribute', value)
There is some interesting memoization I want to do, and this would make the task so much easier. 我想做一些有趣的记忆,这将使任务变得更加容易。
如果您是指实例本身的类,请使用self.__class__
。
In [1]: class A(object):
...: def doStuff(self):
...: c = self.__class__
...: print c, c.__name__
...: setattr(c, 'moo', 'meow')
In [2]: class B(A):
...: pass
...:
In [3]: B().doStuff()
<class '__main__.B'> B
In [4]: B.moo
Out[4]: 'meow'
So, self.__class__
is what you need. 因此,您需要self.__class__
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.