Python:将方法作为函数中的参数传递 [英] Python: pass method as argument in function

查看:27
本文介绍了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())

但是 Python 并不满意:它需要 两个 参数用于 logIn() 函数.很公平.如果认为问题是 getAccount() 方法返回了一个元组,它是 one 对象.我当时试过:

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

但这两者都没有区别.

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

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 :)

感谢您的帮助.本杰明

推荐答案

您想使用 python 参数解包:

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.

当然,您可以手动执行此操作,或者按照其他人的建议编写一个包含元组的包装器,但在这种情况下,解包更有效和 pythonic.

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.

这篇关于Python:将方法作为函数中的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆