LoginSignup
45
29

More than 3 years have passed since last update.

python: getattr

Last updated at Posted at 2019-02-19

pythonでgetattrの使い方がわからなかったので調べました.

実行方法

getattr(宣言したインスタンス名, インスタンス内の関数名)(引数1, 引数2,...)
or
getattr(宣言したインスタンス名, メンバ変数名)

実行の形は上の通り.

単純な挙動

2つ目のかっこに指定された引数を満たした状態で宣言すると,とりあえず関数が実行される.関数に返り値がない場合はNoneTypeになり,もう一回関数として呼ぼうとしても失敗する.逆に引数を与えずに実行すると関数が代入される.

class a():
    def __init__(self):
        self.m = "hoge"

    def no_arg(self):
        print("Got no args.")

    def an_arg(self, b):
        print("Got an arg.")

    def args(self, b, c):
        print("Got a few args.")


cls = a()

a1 = getattr(cls, "no_arg")()
a2 = getattr(cls, "an_arg")(1)
a3 = getattr(cls, "args")(2, 3)
a4 = getattr(cls, "no_arg")
a5 = getattr(cls, "an_arg")
a6 = getattr(cls, "args")

print(getattr(cls, "m"))

a4()
a5(1)
a6(2, 3)
a1()

実行結果

Got no args.
Got an arg.
Got a few args.
hoge
Got no args.
Got an arg.
Got a few args.

Traceback (most recent call last):
  File "test.py", line 27, in <module>
    a1()
TypeError: 'NoneType' object is not callable

こんな使い方?

宣言時に代入した変数は関数内で保持されているので,プチインスタンス的なものを作成可能.

class a():
    def __init__(self):
        pass

    def with_func(self, d):
        print("Got 'with_func() and {}'.".format(d))

        def inside(b, c):
            print("Got {} and {} and {}".format(b, c, d))

        return inside

cls = a()

a1 = getattr(cls, "with_func")(1)

a1(2, 3)
Got 'with_func() and 1'.
Got 2 and 3 and 1
45
29
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
29