【问题标题】:python, how to convert string to class member name? [duplicate]python,如何将字符串转换为类成员名? [复制]
【发布时间】:2022-01-19 10:31:35
【问题描述】:

我想将字符串转换为类成员名称。

我的问题是这样的:

class Constant():
    def add_Constant(self, name, value):
        self.locals()[name] = value  # <- this doesn't work!
    # def
# class

这样做:

CONST = Constant()
CONST.add_Constant(name='EULER', value=2.718)
print(CONST.EULER)

但上面的代码不起作用。有没有办法根据字符串添加类成员?

【问题讨论】:

  • 欢迎来到 Stack Overflow。我链接了一些副本,这些副本解释了在 Python 中解决您的问题的标准工具。但是 - 为什么不just use a dictionary?或enum with custom values,具体取决于您尝试使用Constant 类解决的实际问题

标签: python class oop variables declaration


【解决方案1】:

你可以使用setattr:

class Constant():
    def add_Constant(self, name, value):
        setattr(self, name, value) # <- this does work!

CONST = Constant()
CONST.add_Constant(name='EULER', value=2.718)
print(CONST.EULER)

这个输出:

2.718

【讨论】:

  • 是ʞuɐɥʇ ʎǝɥ 嘿,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
相关资源
最近更新 更多