run_function和run_function_2之间的主要区别是前者对给定给B()构造函数的对象调用foo。^{{/give{6>函数调用的是什么样的函数。例如class A:
def __init__(self,a_var):
self.a_var=a_var
def foo(self):
print(self.a_var)
class B:
def __init__(self, A):
self.A=A
def run_function(self):
self.A.foo()
def run_function_2(self, bar):
bar()
myA = A(42)
myB = B(myA)
myA2 = A(3.14)
myB.run_function()
myB.run_function_2(myA.foo)
myB.run_function_2(myA2.foo)
输出
^{pr2}$
Are there any loopholes that I don't see at the moment?
这两种方法调用方法都很好。虽然我同意function_run_2更方便,因为它不修复方法名,但它会让您问。。。如果一个A对象从未使用过,那么它首先给B构造函数的目的是什么?在The important part is, that the method foo, that is passed, needs to access instance variables of the (its) class instance. So, will foo that is called inside run_function_2 always have access to all instance variables of myA?
是的。run_function_2参数需要函数。在本例中,传递myA.foo,它是在class A中定义的对象{}的方法。当您在run_function_2内部调用foo时,您只处理实例myA的属性变量;这就是在类中封装的思想。在Is there a better way to implement this?
回答你关于安全的问题,这是非常安全的。函数和方法是Python中的对象,它们可以像值一样传递。你基本上依赖于函数currying或部分函数的概念。见How do I pass a method as a parameter in Python。这两种方法都可以。在