“with” in Python


Python Attribute Encapsulation


  • @property should not encapsulate expensive operations, because attribute setting looks cheap
  • @property only controls attributes that are expected


Python Composition


  • Inheritance could be brittle (a change may require changes elsewhere)
  • Decoupled code could work independently or interactively
  • classes interactions will work with an interface
  • Not checking types: polymorphic and Pythonic

Here is an example for inheritance and composition working together:



Python Abstract Class


  • An abstract class is not designed to and can’t not construct instances, but subclassed by regular classes
  • An interface / methods that defined in abstract class must be implement by its subclass
  • The python abc module enables the creation of abstract class


Python Depth-First Order

Multiple inheritance

After Python 2.3, add a role for diamond shape ambiguous inheritance

(Make C inherit A in this example)


Python Class Variable v.s. Instance Attribute

e.g. below set class variable and instance attribute the same name to show the difference and look up order:

  • the attribute look up order: when request an attribute to an instance, it looks for that attribute in the instance first then in the class.

e.g. below how to access class variable in instance:



Python Encapsulation

  • breaking encapsulation: setting the object value without using the setter method


  • enforce encapsulation:


Python Entities

  • class: blueprint for an instance
  • instance: a constructed object of the class
  • type: indicates the class/instance belongs to
  • attribute: value of any object
  • method: a callable attribute defined in the class