类Python3中的继承

时间:2015-04-17 13:39:52

标签: python inheritance nested

我需要这样的东西

class Parent(object): 
    class Base(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b


    class Derived(Base):
        def __init__(self, a, b, c):
            super(Derived,self).__init__(a, b)
            self.c = c

        def doit():
            pass

parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()

当我尝试运行此操作时,出现以下错误:NameError: name 'Derived' is not defined

我试过' Base'取而代之的是'Derived'在super() - 没有帮助

2 个答案:

答案 0 :(得分:2)

类继承不会更改父类。在这种情况下,您的Parent类仅包含原始Base类,而不包含派生类。

你可以简单地使用猴子修补来解决这个问题,

class Parent(object): 
    pass


class Base(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b


class Derived(Base):
    def __init__(self, a, b, c):
        super(Derived,self).__init__(a, b)
        self.c = c

    def doit(self):
        pass

Parent.Derived = Derived

parent = Parent()
x, y , z = 1, 1, 1
derived = parent.Derived(x,y,z)
derived.doit()

答案 1 :(得分:0)

使用'Parent。'前缀'Derived',制作它。正如我已经对这个问题发表了评论。这只是为了试验'Derived'类。但我仍然想知道'class Derived(Base):'是否合适(没有'Parent''前缀为'Base'类)

class Parent(object): 
    class Base(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b


    class Derived(Base):
        def __init__(self, a, b, c):
            super(Parent.Derived,self).__init__(a, b)
            self.c = c

        def doit():
            pass

parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()