首页 > 解决方案 > Python继承,更改基类的初始化成员

问题描述

如果我有一个这样的继承类:

phonebook = {"John": 123, "Rose": 234, "Miles": 345}
class Base(AbstractBase):
    def __init__(self):
        self.phonebook = phonebook

    def doSomething(self):
        aFunctionThatDoesSomething(phonebook)

如果我想使用不同的电话簿,如何继承这个类并调用该函数?我知道我可以将其添加为参数,但是有没有办法在不将其添加到init的情况下做到这一点?

理想情况下,我想编写一个使用已初始化的新值的函数覆盖。所以是这样的:

class Derived(Base):
   def aFunctionThatDoesSomething(self):
       # I want to add some names to the phonebook in the base class here
       self.phonebook = addContacts(self.phonebook)
       super().aFunctionThatDoesSomething()

标签: pythoninheritancederived-classbase-class

解决方案


推荐阅读