代码之家  ›  专栏  ›  技术社区  ›  Rosey

如何在不重写继承的类'\uu init\[duplicate]的情况下向python添加一个

  •  2
  • Rosey  · 技术社区  · 7 年前

    我开始掌握“哎哟”的窍门了。有人能用python上下文向我解释一下这个概念吗?我有几节课:

    class A(object):
        def __init__(self):
            self.foo = 'hello'
    
    class B(A):
        def __init__(self):
            self.bar = 'world'
    

    我想用它自己的init创建一个类B的实例,但我也希望它有a的init。到目前为止,我所知道的唯一能得到我想要的结果的方法就是在B的基础上复制A的init的代码。

    所以我要:

    class A(object):
        def __init__(self):
            self.foo = 'hello'
    
    class B(A):
        def __init__(self):
            self.foo = 'hello'
            self.bar = 'world'
    

    0 回复  |  直到 7 年前