What does this (simple?) expression in Python mean? func(self)(*args) [duplicate]
I saw some Python code like: getattr(self, that)(*args)
. what does it mean? I see that the builtin getattr
function gets called, passing the current object and that
; but what is the (*args)
doing after that? D开发者_运维百科oes it call something with *args
as parameter?
You're right on track. that
is going to be the name of a method on the object. getattr()
is returning that method (function) and then calling it. Because functions are first class members they can be passed around, returned, etc.
It calls the value returned by getattr(self, that)
with the arguments specified in the array args
.
For example, assuming that = 'thatFunction'
and args = [1,2,3]
, it's the same as
self.thatFunction(1, 2, 3)
It calls the method of self whose name is held in that
and passing *args
as the arguments to the function. args
is a tuple and *args
is special syntax that allows you to call a function and expand a tuple into a list of arguments.
Suppose that that
contained the string 'f'
, and args
was (1,2,3)
, then getattr(self, that)(*args)
would be equivalent to:
self.f(1, 2, 3)
getattr()
fetches the attribute of self
named by the string variable that
. The return value, i.e. the attribute named by that
, is then called with the arguments given by the iterable args
.
Assuming that
has the value "foo"
, the following four lines are equivalent:
self.foo(*args)
f = self.foo; f(*args)
f = getattr(self, that); f(*args)
getattr(self, that)(*args)
Using *args
as parameter is the same as using all of the items in args
as spearate parameters.
精彩评论