2015-08-24 16 views
0

在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

+0

'def member_obj.baz'肯定无效。你必须继承'Bar'并将其用于'foo_inst.member_obj'。 – chepner

+0

我把它放在那里来说明我正在努力实现的目标。问题中的“Bar”是'sqlalchemy.Session'。我想避免它的子类化,因为它来自'sessionmaker'函数,所以我将不得不改变它,也可能有其他关系,我不知道这也可能会破坏。我想在'session.expunge'之前添加一些例程来处理我正在执行的混音,所以我无法控制它被调用的时间。如果可能的话,我认为我最好的选择是在mixin中覆盖它。 – mvbentes

回答

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() 
+0

对不起,但没有。我想调用'myOtherObj.value.fun',并将它重新路由以执行除'B.fun'之外的操作。重要的部分是保留这种调用方式:'myOtherObj.value.fun'。正如我在这个问题中指出的,我可以将它包装在一个'A.B_fun_wrapper'中,但我试图避免这个过程。 – mvbentes

+0

啊,我明白了!在这种情况下,你可以在A类的__init()中做self.value.fun = self.fun,因为方法在类内部的任何地方都是可见的,甚至在“def”之前,比如在__init __( ) – Larry

+0

我现在编辑我的答案来指出这一点。另外,我先写了“value = B()”而不是“self.value = B()”,我很抱歉。 – Larry