python - Python 类内部的继承

标签 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:名称“Derived”未定义

我尝试用“Base”代替 super() 中的“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 - Python 类内部的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700880/

相关文章:

python - 将异常主体存储在变量中

Python 日志记录在 Linux 服务器上非常慢......但在 Linux 开发 VM 上很快?

python - pandas 在 csv 上提高 OutOfBoundsDatetime 但不在 sql 上提高 OutOfBoundsDatetime

c# - 无法在没有构造函数定义错误的情况下创建虚拟 C# 传感器类?

cuda - 在我的程序中分配统一内存。运行后,它抛出 CUDA 错误 :out of memory, 但仍有可用内存

jquery嵌套 Accordion 问题

python - 使用 Python 制作可打印的日历

Python继承: create child object in parent class

java - 比较从同一基派生的不同类的对象

ruby-on-rails - Haml 嵌套与 Rails 中渲染的部分