【问题标题】:python static variable in instance method实例方法中的python静态变量
【发布时间】:2013-03-13 18:37:16
【问题描述】:

这是我的代码不起作用

class MyClass:
    special_items = {}
    def preload_items(self):
        special_items['id'] = "properties"

NameError:未定义全局名称“special_items”

作品

class MyClass:
    special_items = {}
    def preload_items(self):
        MyClass.special_items['id'] = "properties"

special_items 不是我可以在此类中的任何位置访问的静态成员吗​​?

【问题讨论】:

    标签: python class variables static


    【解决方案1】:

    python 中没有静态成员这样的东西。你定义的是一个类成员。该成员存储在类对象中,正如您已经展示的那样,它以MyClass.special_items 的形式访问。

    看来您要做的是初始化special_items.,为此,classmethod 更合适(self 没有用处):

    @classmethod
    def preload_items(cls):
            cls.special_items['id'] = "properties"
    

    请注意,您也可以使用self.special_items 访问它,但它仍然存储在类对象上,即类的所有对象都访问相同的值。

    【讨论】:

    • 也许可以为这个建议一个类方法...(或注意self.special_items['id'] 也适用于这个简单的示例)
    • 所以我必须在这个 special_items 之前附加一些东西?在 python 中没有一个干净的方法来调用这个变量?
    • 为什么你认为它不干净?您可以定义一个全局变量,但如果该变量与 MyClass 逻辑关联,则类成员会更好。
    • @wwli:也许指定使用“干净方式”的语言会有所帮助,并具体说明您更喜欢“干净方式”而不是 Python 语义。
    • @bernie 来自 c++ 和 java 显然你可以访问这样一个没有附加任何东西的静态/类变量:)
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2018-08-12
    相关资源
    最近更新 更多