Python:pass方法作为函数中的参数

2024-06-08 06:41:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我看过很多帖子,但没有一篇真正能回答我的问题。在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())

但是Python不高兴:它想要logIn()函数的两个参数。很公平。如果认为问题是getAccount()方法返回了一个元组,它是一个对象。我试过:

def getAccount(self):
    return self.__username, self.__password

但这两者都没什么区别。

那么如何将数据从getAccount()传递到logIn()?当然,如果我不明白这一点,我就错过了编程逻辑中的一些基本内容:)

谢谢你的帮助。 本杰明


Tags: 方法函数self参数returnisdefusername
3条回答

您的方法需要两个参数,而如果要隐藏方法中的登录执行,则可以轻松地传递一个参数,执行该参数并检索数据:

# 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(account):
    user , passwd = account()
   # log into account
   return someData

# run the function from within the myObject instance
myData = myModule.logIn(myObject.getAccount)

注意,传递方法时不带括号,然后在检索数据的登录名中执行该方法。

要使用python argument unpacking

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

函数的参数前的*表示下面的元组应拆分为其组成部分,并作为位置参数传递给函数。

当然,您可以手动执行此操作,也可以按照其他人的建议编写一个带元组的包装器,但对于这种情况,解包效率更高。

这个

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

相关问题 更多 >

    热门问题