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.