如何覆盖成员对象的方法?
How to override a method of a member object?
在python3.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
class 继承没有意义。
如果对象在 Foo
内,我也只希望发生这种不同的行为。我在许多其他地方使用 Bar
并希望保留相同的调用方法的方式。 IE。我想避免将其包装在 Foo.baz
.
中
是否有可能做类似 def member_obj.baz
的事情,这是个好主意吗?
你想做这样的事情吗?
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()
在python3.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
class 继承没有意义。
如果对象在 Foo
内,我也只希望发生这种不同的行为。我在许多其他地方使用 Bar
并希望保留相同的调用方法的方式。 IE。我想避免将其包装在 Foo.baz
.
是否有可能做类似 def member_obj.baz
的事情,这是个好主意吗?
你想做这样的事情吗?
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()