简体   繁体   English

如何从父方法引用子类?

[英]How to refer to a child class from a parent method?

In the following sample, is there a magic word I can put in place of <ChildClass> that works like the opposite of super? 在下面的示例中,是否有一个神奇的词我可以代替<ChildClass> ,它的工作方式与super相反?

class Parent(object):

    def __init__(self):
        print <ChildClass>.x

class someChild(Parent):
    x = 10

It is a stupid example, but it shows my intention. 这是一个愚蠢的例子,但它显示了我的意图。 By the way, using someChild will not work, because there are many child classes. 顺便说一句,使用someChild将无法正常工作,因为有很多子类。

The only solution I can think of is to have a constructor in every child class that calls the constructor of Parent with a reference to itself (or even to pass x), but I would like to avoid having a constructor at all in each child. 我能想到的唯一解决方案是在每个子类中都有一个构造函数,它调用Parent的构造函数并引用它自己(甚至传递x),但我想避免在每个子节点中都有一个构造函数。

What is wrong with just using self.x ? 使用self.x什么问题?

class Parent(object):
    x = None  # default value
    def __init__(self):
        print self.x

class someChild(Parent):
    x = 10
    def __init__(self):
        Parent.__init__(self)

class otherChild(Parent):
    x = 20
    def __init__(self):
        Parent.__init__(self)

a = someChild()
# output: 10
b = otherChild()
# output: 20

Note how this works even if Parent has a class attribute x as well ( None in the above example)- the child's takes precedence. 注意这是如何工作的,即使Parent也具有类属性x (上例中为None ) - 子项优先。

self.x will work if the instance doesn't have an x attribute. 如果实例没有x属性, self.x将起作用。

type(self).x if the instance has an x attribute and you want the class's value, essentially skipping over the instance. type(self).x如果实例具有x属性并且您想要类的值,实际上是跳过实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM