【问题标题】:How to set class attributes in python如何在python中设置类属性
【发布时间】:2019-09-20 03:41:30
【问题描述】:

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

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

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

something = Something(value)

【问题讨论】:

标签: python python-2.7 class-attributes


【解决方案1】:

是的,只是这样做

Something.attribute1 = "some value"    

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2018-08-13
    • 2010-11-01
    • 2012-01-01
    • 2012-06-21
    相关资源
    最近更新 更多