7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで匿名クラス (無名クラス) を作る

Posted at

That's all

obj = type("Hoge", (object,), {
    "var1": 2,
    "var2": "Hello",
    "func1": lambda x: x + 1,
    "func2": lambda self, x: self.var1 * x
})

print(obj.var1, obj.var2)  # 2 Hello
print(obj.func1(2), obj.func2(obj, 2))  # 3 4

others

typeについて

  • 引数が1つの場合、引数の型を返す (type("hello") -> <class 'str'>)
  • 引数が3つの場合、新しい型オブジェクトを返す
    • 1つ目の引数でクラス名 (テキトウで良い) 、2つ目に基底クラスをタプルで渡す
    • 3つ目の引数に、dict型でプロパティ名・値をそれぞれ渡してます (変数でもメソッドでもOKです)

何がしたかったか?

コマンドライン引数をargparseで解析したオブジェクトを引数にしている関数を、Pythonコード内でラクに実行したかった。

  • ↓のhogeのテストコードを書いていた
def hoge(args):
    fuga = args.fuga
    # ...

if __name__ == "__main__":
    parser = argparse.AugmentParser()
    parser.add_argument("--fuga", type=str, required=True)
    # ...
    
    hoge(parser.parse_args())
7
3
2

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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?