如何在python中动态创建类变量 [英] how to create class variable dynamically in python

查看:147
本文介绍了如何在python中动态创建类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一堆类变量,我想通过循环遍历一个列表:

I need to make a bunch of class variables and I would like to do it by looping through a list like that:

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

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

我不想让它们作为一个实例(在__init__中使用self),而是作为类变量。

is it possible? I don't want to make them for an instance (using self in the __init__) but as class variables.

推荐答案

在创建类之后立即运行插入代码:

You can run the insertion code immediately after a class is created:

class Foo():
     ...

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

这篇关于如何在python中动态创建类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆