简体   繁体   English

我想获得一个子类的类

[英]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.

相关问题 我想子类化dict并设置默认值 - I want to subclass dict and set default values 如何获得子类以返回其自身的副本,而不是其继承自的父类? - How can I get a subclass to return a copy of itself, rather than the parent class it is inheriting from? 如何让“mypy”识别 function 的参数需要是特定基础 class 的子类? - How do I get `mypy` to recognize that an argument of a function needs to be a subclass of a particular base class? 如何在子类中调用父类? - How do I call on a parent class in a subclass? Python:如何对要嵌套的类进行子类化? - Python: How can I subclass a class I'm nesting in? 如何使用Python3在目录中获取给定类的所有子类? - How to get all subclass of a given class in a directory with Python3? 如何在一个类中继承 QGraphicsRectItem 和 QGraphicsEllipseItem? - How can I subclass QGraphicsRectItem and QGraphicsEllipseItem in one class? 当我在子类中添加方法时,自动填充类中的列表 - Automatically fill a list in a class when I add a method in a subclass 当我实例化一个python子类时,它会覆盖基类的属性 - When I instantiate a python subclass it overwrites base class' attribute 如何(在运行时)检查一个类是否是另一个类的子类? - How do I check (at runtime) if one class is a subclass of another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM