私はPythonでこのコードに出くわしました.
getattr(self, that)(*args)
どういう意味ですか?組み込み関数 getattr が呼び出され、現在のオブジェクトとその引数が渡されることがわかりますが、その後 (*args) は何をしているのでしょうか?
*args をパラメーターとして呼び出しますか?
編集:ありがとうございました!
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)
あなたは順調です。 that
オブジェクトのメソッドの名前になります。 getattr()
そのメソッド(関数)を返し、それを呼び出しています。関数はファーストクラスのメンバーであるため、受け渡し、返却などを行うことができます。
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.