1

I am a complete Python novice so my question might seem to be dumb. I've seen there are two ways of assigning values to object attributes in Python:

Using __dict__:

class A(object):

    def __init__(self,a,b):
        self.__dict__['a'] = a
        self.__dict__['b'] = b

Without __dict__:

class A(object):

    def __init__(self,a,b):
        self.a = a
        self.b = b

Can anyone explain where is the difference?

4
  • 5
    The second way is better. Commented Aug 5, 2013 at 18:13
  • There is not much difference except that the second one is shorter and clearer (thus more pythonic). Commented Aug 5, 2013 at 18:17
  • 4
    Another problem with __dict__ approach is that it'll also allow you to create attributes like 'a b', but then you can't access such attributes without using __dict__ because a b is an invalid variable name in python. Commented Aug 5, 2013 at 18:19
  • 3
    If you're new just ignore any mention if __dict__. Commented Aug 5, 2013 at 18:26

2 Answers 2

10

Unless you need set attributes dynamically and bypass descriptors or the .__setattr__() hook, do not assign attributes directly to .__dict__.

Not all instances have a .__dict__ attribute even, not if the class defined a .__slots__ attribute to save memory.

If you do need to set attributes dynamically but don't need to bypass a descriptor or a .__setattr__() hook, you'd use the setattr() function normally.

Sign up to request clarification or add additional context in comments.

Comments

2

From the Python documentation:

Both class types (new-style classes) and class objects (old-style/classic classes) are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although for new-style classes in particular there are a number of hooks which allow for other means of locating attributes).

The much more typical way of assigning a new element to a class is your second example, which allows for a number of customizations (__seattr__, __getattr__, etc.).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.