简体   繁体   中英

python static variable in instance method

Here is my code not working

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

NameError: global name 'special_items' is not defined

works

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

Isn't it special_items a static member I can access anywhere in this class?

There is no such thing as static members in python. What you defined is a class-member. The member is stored on the class object, and as you already showed, it is accessed as MyClass.special_items .

It seems that what you're trying to do is to initialize special_items. For that, classmethod is more appropriate (there's no use for self ):

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

Note that you can also access it as self.special_items , but it is still stored on the class object, ie all objects of the class access the same value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM