python - 如何在Python中设置类属性

标签 python python-2.7 class-attributes

我的类中有类属性,我想动态设置它们,这是一个代码示例

class Something:
     attribute1 = 42                 # this is shared between all class instances
     def _init_(self, value):
          self.value = value

我的问题是:有没有办法将该类属性(attribute1)设置为某个值,就像我可以这样设置对象实例属性一样:

something = Something(value)

最佳答案

是的,就这样做

Something.attribute1 = "some value"    

可以通过类名访问类属性。您可以在类中甚至外部定义的任何函数内执行此操作。

关于python - 如何在Python中设置类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55938526/

相关文章:

c# - 'System.Guid' 不是属性类

c# - 我可以将一个类标记为不是我的代码以便调试器跳过它吗?

python - 无法在 Dreamhost 共享主机上使用 Passenger WSGI 运行 Flask

python - ValueError : Unable to coerce to Series, 长度必须为 1:给定 n

python - 没有名为 _version_helper 的模块

python - python寻宝游戏中的无限循环

python - 逐行比较2个文件

python - 在尝试使用 train_test_split 时,我的测试集形状很奇怪

求和列表和数字的 Python 函数

python - 如何使用 tkinter 从另一个类修改一个类中使用的变量?