Python class attributes

Viewed 95

From Yaniv Aknin's post about Python innards: object 102. There is a statement like this.

getting attributes on a type is directly wired to dictionary assignment for the type instance’s private dictionary pointed to by the type’s structure.

I’m struggling to understand what it means.

In the post, it uses the term type over class. So I read it as a class has a type as well and it is type, and type has slots to use the class’s dict to retrieve and set attributes. BUT why getting an attribute is wired to dictionary assignment? Isn’t that suppose to be the set operation?

1 Answers

If you haven't worked with an example yet this may help. An object in python has a special attribute dict which is, "The namespace supporting arbitrary function attributes." dict doc

class Person:
    def __init__(self):
        # self here is person
        # set its attributes age and name
        self.age = 21
        self.name = "Bob"

# person object is of type Person
person = Person()

print( person.__dict__ )
# {'age': 21, 'name': 'Bob'}

# Add a new variable to person object namespace
person.new_var = "a_new_value"

print( person.__dict__ )
# {'age': 21, 'name': 'Bob', 'new_var': 'a_new_value'}

Notice a Person object has the dictionary dict which contains the key value pairs for its attributes.

Related