我有一个 python 问题:
我想将一个方法分配给另一个类的对象,但在这个方法中使用它自己的属性。由于我的项目中有许多具有不同使用方法的容器(不在该示例中),因此我不想使用继承,这将迫使我为每个实例创建一个自定义类。
class container():
def __init__(self):
self.info = "undefiend info attribute"
def use(self):
print self.info
class tree():
def __init__(self):
# create container instance
b = container()
# change b's info attribute
b.info = "b's info attribute"
# bound method test is set as use of b and in this case unbound, i think
b.use = self.test
# should read b's info attribute and print it
# should output: test: b's info attribute but test is bound in some way to the tree object
print b.use()
# bound method test
def test(self):
return "test: "+self.info
if __name__ == "__main__":
b = tree()
非常感谢您阅读本文,也许对我有帮助! :)
干得好。您应该知道 self.test 已经绑定,因为当您进入 __init__ 时,实例已经创建并且其方法已绑定。因此,您必须使用 im_func 成员访问未绑定的成员,并将其与 MethodType 绑定。
import types
class container():
def __init__(self):
self.info = "undefiend info attribute"
def use(self):
print self.info
class tree():
def __init__(self):
# create container instance
b = container()
# change b's info attribute
b.info = "b's info attribute"
# bound method test is set as use of b and in this case unbound, i think
b.use = types.MethodType(self.test.im_func, b, b.__class__)
# should read b's info attribute and print it
# should output: test: b's info attribute but test is bound in some way to the tree object
print b.use()
# bound method test
def test(self):
return "test: "+self.info
if __name__ == "__main__":
b = tree()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)