“with” in Python

發表留言

Python Attribute Encapsulation

Notes:

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

發表留言

Python Composition

Basics

  • 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

basics

  • 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
發表留言