python - 如何扩展类方法

标签 python

SubClassASubClassB 都是 Base 类的子类(都继承自同一个 Base 类)。由于 getInfo() 方法是在 Base() 类中声明的,因此它(此方法)在 A 和 B 子类之间共享。当调用 getInfo() 方法时,它返回 self.attr 变量的值(在 A 和 B 子类之间共享)。现在我想“扩展”这个方法。因此,当使用 instanceA.getInfo() 除了 self.attr 通过 subClassA 实例调用它时,它将返回 self.attrA 也是如此。同样,如果使用instanceB:除了返回self.attr之外,还返回instanceB.getInfo() self.attrB。如何扩展 Base() 类的方法 getInfo() 以便为子类 A 和 B 都“定制”它?

class Base(object):
    def __init__(self):
        super(Base, self).__init__()
        self.attr='Attr'

    def getInfo(self):
        info=self.getAttr()
        return info
    def getAttr(self):
        return self.attr

class SubClassA(Base):
    def __init__(self):
        super(SubClassA, self).__init__()  
        self.attrA='attrA'      
    def getAttrA(self):
        return self.attrA

class SubClassB(Base):
    def __init__(self):
        super(SubClassB, self).__init__()  
        self.attrB='attrB'      
    def getAttrB(self):
        return self.attrB

instanceA=SubClassA()
instanceB=SubClassB()
print instanceA.getInfo()
print instanceB.getInfo()

最佳答案

只需定义 getInfo子类中的方法。如果需要,请使用super (正如您在构造函数中一样)获取基类 getInfo() 的结果并根据需要合并它。

详细说明:给定一个实例时 c某些类别的C ,并要求查找属性 c.attr ,Python 在一系列位置中查找属性。特别是,它将在基类之前查看派生类。因此下面的代码

class Base(object):
    def method(self):
        return "I'm a base object!"

class Derived(Base):
    def method(self):
        return "I'm a derived object!"

obj = Derived()
print obj.method()

将打印“我是派生对象!”,因为Python寻找methodDerived ,找到它,但从未 checkin Base .

您提到需要调用Base.method在你的Derived目的。那就是super进来。super(Derived, self).method()会找到并调用Base.methodself 。您已经在构造函数中这样做了。

例如:

class Computer(object):
    def boot_message(self):
        return 'I am a computer'

class AppleComputer(Computer):
    def boot_message(self):
        return super(AppleComputer, self).boot_message() + ' with a really shiny logo'

我们避免在Computer.boot_message中重复工作。获取其结果并根据需要进行修改。

请注意 super(Base, self).__init__()线路不是必需的;一般来说,只有基类 __init__() 才需要这样的调用派生类 __init__() 确实有效希望在不重复代码的情况下完成,但 object 的情况并非如此。 .

关于python - 如何扩展类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25458433/

相关文章:

python - 使用极轴在 matplotlib 中进行四重显示

python - 如何使用 SQLAlchemy contextmanager 并仍然获得行 ID?

python - 在数据流上运行 Apache Beam 管道会引发错误(DirectRunner 运行没有问题)

python - Xerces + Python?

python - Pandas Dataframe groupby,然后根据菜单或文本选项进行过滤

python - 根据与点的距离过滤坐标

python - 如何让easygui过滤文件列表

c# - 如何使用 C# 执行协程?

Python pandas - 按行选择

python - 错误: 502 bad gateway in flask app on nginx and uwsgi