我创建了一个对象,并分配了非成员函数作为指向其方法之一的指针。现在是否可以从非成员函数访问变量并调用对象的方法?
def process_event():
# How to assess a and b variables and invoke
# foo method specific to that object?
return /*something */
class Testing(object):
def __init__(self, a, b, process_event):
self.a = a
self.b = b
self.process_event_ptr = process_event
def foo(self)
return self.a + self.b
def main():
obj1 = Testing(10, 20, process_event)
obj2 = Testing(100, 200, process_event)
print obj1.process_event_ptr()
print obj2.process_event_ptr()
if __name__ == "__main__"
main()
您可以使用types.MethodType
将process_event
绑定到实例,但实际上您正在动态创建一个新的成员函数,例如:
import types
def process_event(instance):
return instance.foo()
class Testing(object):
def __init__(self, a, b, process_event):
self.a = a
self.b = b
self.process_event_ptr = types.MethodType(process_event, self)
def foo(self):
return self.a + self.b
obj1 = Testing(10, 20, process_event)
obj2 = Testing(100, 200, process_event)
print(obj1.process_event_ptr())
print(obj2.process_event_ptr())
Out[]:
30
300