创建动态类属性

huangapple go评论60阅读模式
英文:

Create dynamic class attributes

问题

I have a predefined class. I want to create class attributes whose names can be decided at run time only.
Outside of the class, I append my required name into the globals() dict, but how to do the same for classes.

My attempt at it is given below:

class test:
 def __init__(self,x):
  globals()[x]=''

The result was a global variable added instead of a class variable.

英文:

i have a predefined class. I want to create class attributes whose names can be decided at run time only.
outside of class i append my required name into the globals() dict but how to do the same for classes

my attempt at it is given below:

class test:
 def __init__(self,x):
  globals()[x]=''

the result was a global variable added instead of class variable

答案1

得分: 1

你可以使用__dict__属性,它类似于globals(),但适用于类的局部实例。

class test:
    def __init__(self, x):
        self.__dict__[x] = ''
英文:

you can use the __dict__ attribute which acts like a globals() but for a localized instance of a class

class test:
 def __init__(self,x):
  self.__dict__[x]=''

答案2

得分: 1

Use setattr.

class Test:
    def __init__(self, x):
        setattr(self, x, '')
英文:

Use setattr.

class Test:
    def __init__(self, x):
        setattr(self, x, '')

huangapple
  • 本文由 发表于 2023年5月14日 21:55:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定