web-dev-qa-db-ja.com

python)でクラス変数を動的に作成する方法

たくさんのクラス変数を作成する必要があり、次のようなリストをループして作成したいと思います。

vars=('tx','ty','tz') #plus plenty more

class Foo():
    for v in vars:
        setattr(no_idea_what_should_go_here,v,0)

出来ますか?インスタンス用に(__init__でselfを使用して)作成するのではなく、クラス変数として作成します。

20
pawel

クラスが作成された直後に挿入コードを実行できます。

class Foo():
     ...

vars=('tx', 'ty', 'tz')  # plus plenty more
for v in vars:
    setattr(Foo, v, 0)

また、クラスの作成中に変数を動的に保存できます。

class Bar:
    locals()['tx'] = 'texas'
34

何らかの理由で、クラスの作成後にそれらを設定するというレイモンドの答えを使用できない場合は、おそらくメタクラスを使用できます。

class MetaFoo(type):
    def __new__(mcs, classname, bases, dictionary):
        for name in dictionary.get('_extra_vars', ()):
            dictionary[name] = 0
        return type.__new__(mcs, classname, bases, dictionary)

class Foo(): # For python 3.x use 'class Foo(metaclass=MetaFoo):'
    __metaclass__=MetaFoo # For Python 2.x only
    _extra_vars = 'tx ty tz'.split()
7
Duncan

パーティーに遅れますが、 typeクラスコンストラクター を使用してください!

Foo = type("Foo", (), {k: 0 for k in ("tx", "ty", "tz")})
5
costrouc

locals()バージョンはクラスで機能しませんでした。

以下を使用して、クラスの属性を動的に作成できます。

class namePerson:
    def __init__(self, value):
        exec("self.{} = '{}'".format("name", value)

me = namePerson(value='my name')
me.name # returns 'my name'
0