python怎么向函数传递参数_的Python:传递方法,在函数参数

I've seen a lot of posts but none really addressing my question. With Python, I am trying to pass a method as an argument in a function which requires two arguments:

# this is a method within myObject

def getAccount(self):

account = (self.__username, self.__password)

return account

# this is a function from a self-made, imported myModule

def logIn(username,password):

# log into account

return someData

# run the function from within the myObject instance

myData = myModule.logIn(myObject.getAccount())

But then Python's not happy: it wants two arguments for the logIn() function. Fair enough. If thought the problem was that the getAccount() method returned a tuple, which is one object. I tried then:

def getAccount(self):

return self.__username, self.__password

But that either did not make a difference.

How then can i pass the data from getAccount() to logIn()? Surely if i don't understand that, i am missing something fundamental in the logic of programming :)

Thanks for helping.

Benjamin

解决方案myData = myModule.logIn( * myObject.getAccount() )

The * before an argument to a function signals that the following tuple should be split into its constituents and passed as positional arguments to the function.

Of course, you could do this by hand, or write a wrapper that takes a tuple as suggested by others, but unpacking is more efficient and pythonic for this case.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值