英文:
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, '')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论