2: Variables, Objects and Attributes

Summary

  • An object is a collection of attributes

  • variables reference objects, which have a lifetime of their own independent of any variable referencing them

  • An object can be referenced by many variables and so has no fixed and immutable name.

  • An attribute is a reference to an object

Pythons approach

  • Names are just variables that store references

  • A variable is created by simply using it

  • variables are dynamic, untyped and are references to objects

Creating Objects

class MyObject:
    myAttribute = 1


#access using dot notation

print(MyObject.myAttribute) # prints 1
MyObject.myAttribute = 2
print(MyObject.myAttribute) # prints 2

# add an attribute
MyObject.myNewAttr = 7

# del an attribute
del MyObject.myNewAttr

Nested Objects

class MyObject1:
    myAttribute1 = 1
    class MyObject2:
        myAttribute2 = 2

#access
MyObject1.MyObject2.myAttribute2

#use a variable to store the reference
myRef = MyObject1.MyObject2
myRef.myAttribute2

Modules

import myModule.MyObject # imports just the object
import myModule.MyObject as MySecondObj #imports the same object but changes the variable that references it

Namespaces

  • Every object has a __dict__ attribute that is its local namespace

  • It records all the objects attributes

  • Internally an attribute is looked up in the object dictionary so:

print(MyObject.myAttribute)

# is equal to:

print(MyObject.__dict__["myAttribute"])