Skip to main content
 首页 » 编程设计

python之类 Python 中的继承

2024年10月25日11webabcd

我需要这样的东西

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()