python实例作为参数_如何将使用实例变量的实例方法作为参数传递给另一个函数?...

本文探讨了如何将包含实例变量的Python实例方法作为参数传递给其他函数,通过`run_function`和`run_function_2`两个示例函数展示了不同的调用方式。`run_function_2`提供了更大的灵活性,但可能引发对于对象创建目的的疑问。关键在于,传递的方法(如`foo`)在被调用时仍能访问其所属实例的变量。这种做法在Python中是安全的,因为方法是可作为值传递的对象,类似于函数柯里化或部分应用的概念。
摘要由CSDN通过智能技术生成

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。这两种方法都可以。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值