Ben*_*min 5 python methods arguments
我看过很多帖子,但没有一个真正解决我的问题.使用Python,我试图在一个需要两个参数的函数中将方法作为参数传递:
# 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())
Run Code Online (Sandbox Code Playgroud)
但是后来Python不高兴:它想要logIn()函数的两个参数.很公平.如果认为问题是getAccount()方法返回了一个元组,它是一个对象.我试过了:
def getAccount(self):
return self.__username, self.__password
Run Code Online (Sandbox Code Playgroud)
但这要么没有任何区别.
那么如何将getAccount()中的数据传递给logIn()?当然,如果我不明白,我错过了编程逻辑中的一些基本内容:)
谢谢你的帮助.本杰明
你想使用python参数解包:
myData = myModule.logIn( * myObject.getAccount() )
Run Code Online (Sandbox Code Playgroud)
的*
一个参数,下面的元组应当被分成其组分和作为位置参数传递给函数的函数信号之前.
当然,您可以手动执行此操作,或者编写一个包含其他人建议的元组的包装器,但对于这种情况,解包更有效率和pythonic.
归档时间: |
|
查看次数: |
5665 次 |
最近记录: |