0

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?

asked Mar 13, 2013 at 18:37

1 Answer 1

2

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, i.e. all objects of the class access the same value.

answered Mar 13, 2013 at 18:38
Sign up to request clarification or add additional context in comments.

8 Comments

Maybe suggest a classmethod for this one ... (or note that self.special_items['id'] will also work out for this simple example)
So I have to attach something before this special_items? No a clean way to call this variable in python?
Why do you consider it not clean? You can define a global variable, but if the variable is logically-associated with MyClass, class member is way better.
@wwli: Perhaps it would be helpful to specify the language in which a "clean way" is used, and explain what specifically about that "clean way" you prefer over Python's semantics.
@bernie from c++ and java apparently you can access such a static/class variable with nothing attached :)
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.