LPTHW - Day 145 Gothons Are Getting Classy - Part 3

Part 3 on exercise 42 of LPTHW. Today is all about `__dict__` attribute in  Python  object. Several special properties about this attribute.

a) This special attribute is one of the five predefined attributes of a class. There other fours are `__name__`, `__bases__`, `__doc__`, and `__module__`.

b) As the name (dict) implies, this attribute is a dictionary object (Note to self: remember, almost everything is an object in Python), one of the built-in data type in Python. A dictionary is a set of key:value pairs surrounded by braces. Example is `{'foo' : 1, 'bar' : 2, 'baz' : 3}`.

Example 0:
>>> class Foo(object):
........ pass

>>> f = Foo()
>>> f.a = 'a'
>>> f.b = 'b'
>>> f._dict_
{'a': 'a', 'b': 'b'}

c) Namespace is a container that stores a set of identifiers. A container ensures uniqueness and hierarchy to all identifiers. Using a dictionary object which support these two characteristics, you can implement (identifies as keys, different data types as values ) a namespace in both modules and classes in Python. Some examples 3 of common namespace usage:

Example 1:
identifier /home/kianmeng/.bashrc (unique location)
namespace /home/kianmeng (path)
local name .bashrc (file name)

Example 2:
identifies www.example.com (url)
namespace example.com (domain)
local name www (host name)

d) Object attributes referencing and assignment can be done in both ways of dot notation or direct dictionary manipulation. Comparison of both are shown below:

Example 3: Dot notation
a = o.foo
o.foo = b

Example 4: Direct dictionary manipulation
a = o.___dict___["foo"]
o.___dict___["foo"] = a

e) If an attribute is not found in current child class __dict__ object, Python will lookup the attribute in the parent class `__dict__` object. Attribute assignment only can be done within the current child class and not the parent class.

No comments:

Post a Comment