我需要这样的东西
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
我在
super()
中用'Base'代替了'Derived'-没有帮助 最佳答案
类继承不会更改父类。在这种情况下,您的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()
关于python - 类Python3内部的继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29700880/