Permalink
Browse files

add open closed principle in python explanation

  • Loading branch information...
1 parent f470e36 commit b854179684102a01a11222fbca22183f7fc4585d @LMMilewski committed Mar 18, 2012
Showing with 33 additions and 2 deletions.
  1. +16 −2 README.org
  2. +17 −0 open_closed_dict.py
View
@@ -160,6 +160,20 @@
+ using flags=re.X (re.VERBOSE) you can write regexps that don't
look like result of MD5 function. You can write regexp in
multiple lines and add comments using # as usually. [[http://docs.python.org/library/re.html#re.X][re.X documentation]]
-* Subclassing patterns
+* Subclassing
- [[http://www.youtube.com/watch?NR%3D1&feature%3Dendscreen&v%3DmiGolgp9xq8][Talk from PyCon2012]]
- - dynamic_dispatch.py
+ - classes are dictionaries of functions
+ - subclasses point to other dictionaries to reuse their code
+ - subclasses are in complete control of what happens
+ - [[https://github.com/lmmilewski/learn_python/blob/master/dynamic_dispatch.py][dynamic_dispatch.py]]
+ - LSP (Liskov Substitution Principle)
+ - "If S is a subtype of T, then objects of type T may be replaced
+ with objects of type S"
+ - LSP is usefull. but it's ok (and common) to violate it (list
+ can't be substituted by array due to constructor args)
+ - OCP (Open-Closed Principle)
+ - "Objects have internal invariants and subclasses shouldn't be
+ able to break those invariants"
+ - In other words, the classes capabilities can be extended but the
+ underlying class shouldn't get broken
+ - [[https://github.com/lmmilewski/learn_python/blob/master/][open_closed_dict.py]]
View
@@ -0,0 +1,17 @@
+# Subclasses should not be able to brake superclasses
+
+class MyDict(object):
+ def __init__(self, iterable):
+ self.item_list = []
+ # we don't want to call update here, because if subclass
+ # overrides update it can break __init__ which is not expected
+ # behaviour by the subclass
+ self.__update(iterable)
+
+ def update(self, iterable):
+ for item in iterable:
@mmilewski
mmilewski Mar 30, 2012

how about

self.items_list.extend(iterable)
?

@LMMilewski
LMMilewski Mar 31, 2012 owner

If you say that the loop could (and probably should) be replaced by one line that you show then I agree. Feel free to create pull request and I will apply it.

I don't see how that relates to Open-Closed principle though.

+ self.items_list.append(item)
+
+ # instead we do little trick that makes sure you can't override
+ # update called by init while you can override update itself
+ __update = update

0 comments on commit b854179

Please sign in to comment.