如何覆盖成员对象的方法?

时间:2015-08-24 17:15:20

标签: python design-patterns composition

在python 3.4中,我通过合成创建了一个成员对象。

我想覆盖其中一个成员函数。

def class Foo:
    def __init__(self, value):
        self.value = value
    def member_obj.baz(baz_self, arg):
        print("my new actions on {}".format(arg))
        Foo.member_obj.baz(arg) #the original function

foo_inst = Foo(2)
bar = Bar(*bar_parameters) #from a third party module
setattr(foo_inst, "member_obj", bar) #it did not "stick" when I did foo_inst.member_obj = bar

foo_inst.member_obj.baz("some argument")

Bar类继承是没有意义的。 如果对象位于Foo内,我也只想要发生这种不同的行为。我在许多其他地方使用Bar,并希望保留调用该方法的相同方式。即我想避免将其包装在Foo.baz

甚至可以做def member_obj.baz这样的事情,这是个好主意吗?

它类似于:https://softwareengineering.stackexchange.com/questions/150973/what-are-the-alternatives-to-overriding-a-method-when-using-composition-instea

1 个答案:

答案 0 :(得分:1)

你想做这样的事吗?

class B():
    def __init__(self):
        self.x = None
    def fun(self):
        print("Assigning value to attribute of object of class B.\n")
        self.x = "Value of B object's attribute"
class A():
    def __init__(self):
        self.value = B()
    def fun(self):
        print("Screw this, I'll do something else this time!\n")
        self.value.x = 13
    def override(self):
        # Edit: you can assign any identifier (that is not reserved) to
        # any type of object or method AND the "fun" ("really self.fun") 
        # above is visible from here, since we passed "self" as an
        # argument
        self.value.fun = self.fun

myObj = B()
myOtherObj = A()
myOtherObj.override()

myObj.fun()
myOtherObj.value.fun()