Describing Object Representation
- Internally, instances are implemented using a dictionary
- This dictionary is accessible using the
__dict__attribute - This dictionary contains the data unique to each instance
>>> a = Account('Todd', 10)
>>> a.__dict__
{'balance': 10, 'name': 'Todd'}- Modifications to an instance are always reflected in
__dict__ - Instances are also linked back to their class using
__class__ - Classes are linked back to their base class using
__bases__
Details about Special Methods
- Whenever an attribute is set using
obj.name=value, the special methodobj.__setattr__('name', value)is invoked -
The same goes for the following:
obj.name=valinvokesobj.__setattr__('name', val)del obj.nameinvokesobj.__delattr__('name')obj.nameinvokesobj.__getattribute__('name')
Restriction of Setting Instance Attributes
- A class can restrict the set of legal instance attribute names by defining
__slots__ - When
__slots__is defined, instance can't assign new attributes unless the attribute is specified in__slots__ - This restriction prevents someone from adding new attributes to instances
- The use of
__slots__can hurt the performance of classes using inheritance
References
Previous
Next