SlideShare a Scribd company logo
Dynamic Python Think Dynamic [email_address]
Python Advertising What Programmers and enterprise says about using Python. Speed/Memory usage when compare Python with other languages.
Master says…. Python Is OOP Done Right  – “ Programming Python”,21.6.3 Perl is worse than Python because people wanted it worse.  -- Larry Wall  I can remember many Python idioms because they're simpler. That's one more reason I program faster [in Python]. I still have to look up how to open a file every time I do it in Java. In fact, most things in Java require me to look something up.    -- Bruce Eckel
Master says….      (cont.) Python ... is compact -- you can hold its entire feature set (and at least a concept index of its libraries) in your head.  -- Eric S. Raymond "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at  Google, Inc.
Master says…. (cont.) "NASA is using Python to implement a CAD/CAE/PDM repository and model management, integration, and transformation system which will be the core infrastructure for its next generation collaborative engineering environment. … said Steve Waterbury, Software Group Leader,  NASA STEP  Testbed .
Master says…. (cont.) "Python enabled us to create  EVE Online , a massive multiplayer game, in record time. The EVE Online server cluster runs over 25,000 simultaneous players in a shared space simulation, most of which is created in Python. The flexibilities of Python have enabled us to quickly improve the game experience based on player feedback," said Hilmar Veigar Petursson of  CCP Games .
http://shootout.alioth.debian.org/gp4/benchmark.php?test= all&lang =perl&lang2=python
http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=php&lang2=python
http://shootout.alioth.debian.org/gp4/benchmark.php?test= all&lang =java&lang2=python
http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ruby&lang2=python
http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=gpp&lang2=python
http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=gpp&lang2=java
Today’s topic Python doesn't have ‘Char’ type - Sequence - Slice Dynamic Python features – an brief introduction - name-based polymorphism - Duck typing
One Minute Python Tutorial import os def do_func(): my_list = ['hello','world', 2 ,'python!'] for x in my_list: print x, a='ls -al' if a=='ls -al': do_func() os.system(a)
Choice – If …..and only if …. if python == quick_enough_for_you: python=your_primary_language else: python=your_glue_language Use Indent – NO curly brackets  {   }   Some keyword: pass,elif,and,or,not No Switch. z=b if a<b else z=a (python 2.5,pep308)
 
Five Minutes Python Deploy Demo Bulid Native Python Program (ELF,EXE) freeze.py, py2exe (win32 only), pyinstaller Build python script to windows EXE format on Linux via wine and pyinstaller Cross Compile Python via crosspy script. Setup a GNU toolchain(binutils,compiler). Cross compile Python module is a little harder. Python is so SMALL for LOTS features it supply. really...
Topic 1 String, Slice
Python String Python doesn’t have a Char type 。   String Python String is  - a object - a sequence of characters x = “Hello World” type(x)    <type ‘str’> y = str(“Hello World”)
Manipulate strings (type str) Invoke Python Interpreter x = ‘Hell’+’o’  #no plus works too x ‘ ==‘+x*5+’==‘ x[3] x[0:2] #slice is slight different x[:2] # then element access
Slices 0  1  2  3  4  5 -5  -4  -3  -2  -1 This is so called “Slice “ syntax [A:B] o l l e H
Manipulate strings (cont.) x[2:] x[1:100] #python knows boundary x[2:1] #return “”,always [begin:end] x[-1] x[-2:] x[:-2]
Manipulate string  (cont.) s = 'supercalifragilisticexpialidocious' len(s) 'ab' in 'abcd'   #return true. '  abc    '.strip()    ’abc’ '><><abc<><><>'.strip('<>')    ’abc’ '><><abc<><><>'.strip('<>')    same str '45'.zfill(4)    ’0045’ dir( '' )  ==> help()
Topic 2 List, Sequence, Iterator
List Show = [‘hello’,’world’,1,999] Show Show[0] Show[3] Show[3]=Show[3]+255 Show[1:3] # slice can work on list   Show[:2]+[“wow”,”hey”]+3*show[:1]
Slices advanced. (python 2.3↑) L = range(10)   L[1:7:2]  --  [1,3,5] L[::2]  --  [0,2,4,6,8]   L[::-1]   --  reverse list del L[::2]   --  [1,3,5,7,9] range(10)[slice(0, 5, 2)]   -- [0,2,4] range(10).__getitem__(slice(0, 5, 2))
Sequence An  iterable  which supports efficient element access using integer indices via the __getitem__() and __len__() special methods. Some built-in sequence types are list, str, tuple. Note that dict also supports __getitem__() and __len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary  immutable  keys rather than integers.
iterator  An object representing a stream of data. Repeated calls to the iterator's next() method return successive items in the stream.  When no more data is available a StopIteration exception is raised instead. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop.
How Java iterate Sequence (Collection, Array) for ( Iterator  i = c.iterator(); i.hasNext(); ) {  String  s = ( String ) i.next();  ...  }  Java 1.5↑(JSR 201): for ( String  s : c)    JAVA 1.5 { ... }  for s in c:     Python …
iterable  A container object capable of returning its members one at a time.  for x in range(0, 10): print x When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you.
Iterable demo x=[1,2,3] iter(x) i=x.__iter__() i.next() Implement your __iter__() and next() method then you can get a Iterable
Sequence (summary) A  iterable  supports indexing, slicing, and being passed to the built-in function len. Iterables that are not sequences include dictionaries (iteration gives the keys of the dictionary, one at a time in arbitrary order), file objects (iteration gives the lines of the text file, one at a time), and many more, including iterators and generators.
Topic 3 Namespace, Polymorph
A simple question… String foo = “foo”; What is the type of foo? Type String ?  (type == class) String tim;  tim has type 'String‘. tim can only reference objects that are class String…….in C++ & java tim – for python, is a name. and it’s just a name. (or you might want to call it object reference, in java or C++, whatever.)
Namespace Namespaces are one honking great idea -- let's do more of those! – The Zen of Python Basic “three-scope rule” (builtin/global/local), (However Python 2.1 add nested scoping) 。 x=“Hello World” If “Hello World” doesn’t exist, python create it. If “Hello World” exist, python locate it. x is a name. “Hello World” is a string object.
Namespace (cont.) If the name x doesn’t exist in current namespace, the name x is bound to “Hello World”  。 If a name x is exist in current namespace, it is rebound 。 Multiple names can bound to same object 。 BTW: x = y means dereference y and bound to name x 。
Python Mind Testing Problem A=1 A=“HELLO” just changed type ? NO! the A itself is not “an object”, it’s a name. Create an integer object with the value 1 and bind the name ‘A' to it.  Then create a new string object with the value HELLO, and rebind the name ‘A' to it.
Python Mind Testing Problem(cont.) Object reference  --  name without type. Object  --  typed. Python is dynamically but strongly typed. dynamically typed: the reference (“name”) strongly typed: objects  don't change type   Historically, &quot;strong typing&quot; has been associated with static typing.
name-based polymorphism .  type based polymorphism (C++,Java) name-based polymorphism. (smalltalk) Python’s “Polymorphism” is NOTHING to do with inheritance. As said, Python variables do NOT have a type. Python can use one variable to hold any kind of objects.
show() Base x=A()  #you can also try this class Base; x.show()  array = [ A(),B(),C() ]  class A extends Base; x=B()  for x in array:    class B extends Base; x.show() x.show() class C extends Base; x=C() Base x; x.show()  x= new B(); x.show(); or  interface Base, whatever. show() A show() B show() C
Topic 4 Duck Typing
duck-typing   If it looks like a duck and quacks like a duck, it must be a duck. – duck test Quack quack quack! Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object. Won’t rely on inheritance to do polymorph 。
duck-typing (cont.) it doesn't actually  matter  what type my data is - just whether or not I can do what I want with it. if isinstance(myobject, dict):     value = myobject[member]  try:      value = myobject[member] except TypeError:     # do something else  Not pythonic
OK, What’s WRONG about  “Just Check type” ? def isExactlyAString(anobj):  return type(anobj) is type('')  You reject Unicode objects, instances of user-coded subclasses of str, and instances of any user-coded type that is meant to be “string-like” 。 def isStringLike(anobj):  try: anobj + ''  except: return False  else: return True
Quick list and dict syntax x = [0,1,2, 3]  x[2]  list.__getitem__(x, 2)  x.__getitem__(2) b = {'a': 0, 'b': 1}  b['a']  dict._getitem__(b, 'a')  b.__getitem__(‘a’)
Duck typing (cont.) x[2] Python don’t care about x’s type 2 If __getitem__ return “quack!” x must be a duck!   if __getitem__ return something meaningless, then an error generaterd.
Do you see convenient? myobject = ComplexClass(filename) value = myobject['member 1'] value2 = myobject['member 2']  Python don’t care what type myobject is. As long as myobject.__getitem__(“member 1”) get something useful. You can just use [‘’] dict syntax to do something really complex in your class.
Python is TOO DYNAMIC,  Can I have a real constants? Any variable can be re-bound in python 。 But…modules don‘t let you do it 。 const.py class _const:  class ConstError(TypeError): pass  def __setattr__(self,name,value):  if self.__dict__.has_key(name):  raise self.ConstError,”Error!” self.__dict__[name]=value import sys sys.modules[__name__]=_const() import const  const.magic = 23  const.magic = 99 (Error!)
Topic 5 Some Pattern
And… Singleton Pattern?  “ Singleton Pattern” ensuring that just one instance of a certain class is ever created.  singleton.py: &quot;&quot;&quot;This module implements singleton &quot;&quot;&quot;  Python modules are Singleton instances 。 import singleton singleton.XXX Cons: doesn't have a class, can't inherit, and can't be inherited from. It also requires a seperate Python file 。
__new__ first step in instance construction, invoked  before  __init__()  。 return a new instance of that class  。 called with the class as its first argument 。  __init__ () is called with an instance as its first argument, and doesn‘t return anything 。 responsibility of __init__() is to initialize the instance 。
Classic Singleton Pattern class Singleton(object):  def __new__(type):  if not '_instance' in type.__dict__:    type._instance=object.__new__(type)  return type._instance a=Singleton() b=Singleton() print a==b --> True
Python’s Borg Pattern class Borg:  __shared_state = {}  def __init__(self):  self.__dict__ = self.__shared_state # and whatever else you want in your class -- that's all!  Many instances, all share same state. Who cares about *identity* -- it's *state* (and behavior) we care about!
For those Getter and setters… okokok, python DO have it… Properties: attributes managed by get/set methods 。 class C(object):  def __init__(self): self.__x = 0  def getx(self): return self.__x  def setx(self, x):    if x < 0: x = 0    self.__x = x  x = property(getx, setx)   a.x=-10    a.x == 0
The Factory pattern? Fact: __init__ can’t return objects. Just use a function to generate objects. Actually…we can even generate a class…
inherit  in python B(A) => B inherit A means : lookup B attributes(data objects or function objects) that are not found in A 。 Constructor isn’t any special stuff in python 。 A class is ALREADY an object after the class body end 。 (no instance yet)
class factory  function def class_with_method(func):  class klass: pass  setattr(klass, func.__name__, func)  return klass def say_foo(self): print 'foo'  Foo = class_with_method(say_foo)  foo = Foo()  foo.say_foo()  => foo
Topic 6 Python is MUCH POWERFUL   than what I introduced,  TRY IT yourself.
Thank You! Present by Python fans: [email_address] To be continued….

More Related Content

Dynamic Python

  • 1. Dynamic Python Think Dynamic [email_address]
  • 2. Python Advertising What Programmers and enterprise says about using Python. Speed/Memory usage when compare Python with other languages.
  • 3. Master says…. Python Is OOP Done Right – “ Programming Python”,21.6.3 Perl is worse than Python because people wanted it worse. -- Larry Wall I can remember many Python idioms because they're simpler. That's one more reason I program faster [in Python]. I still have to look up how to open a file every time I do it in Java. In fact, most things in Java require me to look something up. -- Bruce Eckel
  • 4. Master says….    (cont.) Python ... is compact -- you can hold its entire feature set (and at least a concept index of its libraries) in your head. -- Eric S. Raymond &quot;Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language.&quot; said Peter Norvig, director of search quality at Google, Inc.
  • 5. Master says…. (cont.) &quot;NASA is using Python to implement a CAD/CAE/PDM repository and model management, integration, and transformation system which will be the core infrastructure for its next generation collaborative engineering environment. … said Steve Waterbury, Software Group Leader, NASA STEP Testbed .
  • 6. Master says…. (cont.) &quot;Python enabled us to create EVE Online , a massive multiplayer game, in record time. The EVE Online server cluster runs over 25,000 simultaneous players in a shared space simulation, most of which is created in Python. The flexibilities of Python have enabled us to quickly improve the game experience based on player feedback,&quot; said Hilmar Veigar Petursson of CCP Games .
  • 13. Today’s topic Python doesn't have ‘Char’ type - Sequence - Slice Dynamic Python features – an brief introduction - name-based polymorphism - Duck typing
  • 14. One Minute Python Tutorial import os def do_func(): my_list = ['hello','world', 2 ,'python!'] for x in my_list: print x, a='ls -al' if a=='ls -al': do_func() os.system(a)
  • 15. Choice – If …..and only if …. if python == quick_enough_for_you: python=your_primary_language else: python=your_glue_language Use Indent – NO curly brackets { } Some keyword: pass,elif,and,or,not No Switch. z=b if a<b else z=a (python 2.5,pep308)
  • 16.  
  • 17. Five Minutes Python Deploy Demo Bulid Native Python Program (ELF,EXE) freeze.py, py2exe (win32 only), pyinstaller Build python script to windows EXE format on Linux via wine and pyinstaller Cross Compile Python via crosspy script. Setup a GNU toolchain(binutils,compiler). Cross compile Python module is a little harder. Python is so SMALL for LOTS features it supply. really...
  • 19. Python String Python doesn’t have a Char type 。  String Python String is - a object - a sequence of characters x = “Hello World” type(x)  <type ‘str’> y = str(“Hello World”)
  • 20. Manipulate strings (type str) Invoke Python Interpreter x = ‘Hell’+’o’ #no plus works too x ‘ ==‘+x*5+’==‘ x[3] x[0:2] #slice is slight different x[:2] # then element access
  • 21. Slices 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is so called “Slice “ syntax [A:B] o l l e H
  • 22. Manipulate strings (cont.) x[2:] x[1:100] #python knows boundary x[2:1] #return “”,always [begin:end] x[-1] x[-2:] x[:-2]
  • 23. Manipulate string (cont.) s = 'supercalifragilisticexpialidocious' len(s) 'ab' in 'abcd' #return true. ' abc '.strip()  ’abc’ '><><abc<><><>'.strip('<>')  ’abc’ '><><abc<><><>'.strip('<>')  same str '45'.zfill(4)  ’0045’ dir( '' ) ==> help()
  • 24. Topic 2 List, Sequence, Iterator
  • 25. List Show = [‘hello’,’world’,1,999] Show Show[0] Show[3] Show[3]=Show[3]+255 Show[1:3] # slice can work on list  Show[:2]+[“wow”,”hey”]+3*show[:1]
  • 26. Slices advanced. (python 2.3↑) L = range(10) L[1:7:2] -- [1,3,5] L[::2] -- [0,2,4,6,8] L[::-1] -- reverse list del L[::2] -- [1,3,5,7,9] range(10)[slice(0, 5, 2)] -- [0,2,4] range(10).__getitem__(slice(0, 5, 2))
  • 27. Sequence An iterable which supports efficient element access using integer indices via the __getitem__() and __len__() special methods. Some built-in sequence types are list, str, tuple. Note that dict also supports __getitem__() and __len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers.
  • 28. iterator An object representing a stream of data. Repeated calls to the iterator's next() method return successive items in the stream. When no more data is available a StopIteration exception is raised instead. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop.
  • 29. How Java iterate Sequence (Collection, Array) for ( Iterator i = c.iterator(); i.hasNext(); ) { String s = ( String ) i.next(); ... } Java 1.5↑(JSR 201): for ( String s : c)  JAVA 1.5 { ... } for s in c:  Python …
  • 30. iterable A container object capable of returning its members one at a time. for x in range(0, 10): print x When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you.
  • 31. Iterable demo x=[1,2,3] iter(x) i=x.__iter__() i.next() Implement your __iter__() and next() method then you can get a Iterable
  • 32. Sequence (summary) A iterable supports indexing, slicing, and being passed to the built-in function len. Iterables that are not sequences include dictionaries (iteration gives the keys of the dictionary, one at a time in arbitrary order), file objects (iteration gives the lines of the text file, one at a time), and many more, including iterators and generators.
  • 33. Topic 3 Namespace, Polymorph
  • 34. A simple question… String foo = “foo”; What is the type of foo? Type String ? (type == class) String tim; tim has type 'String‘. tim can only reference objects that are class String…….in C++ & java tim – for python, is a name. and it’s just a name. (or you might want to call it object reference, in java or C++, whatever.)
  • 35. Namespace Namespaces are one honking great idea -- let's do more of those! – The Zen of Python Basic “three-scope rule” (builtin/global/local), (However Python 2.1 add nested scoping) 。 x=“Hello World” If “Hello World” doesn’t exist, python create it. If “Hello World” exist, python locate it. x is a name. “Hello World” is a string object.
  • 36. Namespace (cont.) If the name x doesn’t exist in current namespace, the name x is bound to “Hello World” 。 If a name x is exist in current namespace, it is rebound 。 Multiple names can bound to same object 。 BTW: x = y means dereference y and bound to name x 。
  • 37. Python Mind Testing Problem A=1 A=“HELLO” just changed type ? NO! the A itself is not “an object”, it’s a name. Create an integer object with the value 1 and bind the name ‘A' to it. Then create a new string object with the value HELLO, and rebind the name ‘A' to it.
  • 38. Python Mind Testing Problem(cont.) Object reference -- name without type. Object -- typed. Python is dynamically but strongly typed. dynamically typed: the reference (“name”) strongly typed: objects don't change type Historically, &quot;strong typing&quot; has been associated with static typing.
  • 39. name-based polymorphism . type based polymorphism (C++,Java) name-based polymorphism. (smalltalk) Python’s “Polymorphism” is NOTHING to do with inheritance. As said, Python variables do NOT have a type. Python can use one variable to hold any kind of objects.
  • 40. show() Base x=A() #you can also try this class Base; x.show() array = [ A(),B(),C() ] class A extends Base; x=B() for x in array: class B extends Base; x.show() x.show() class C extends Base; x=C() Base x; x.show() x= new B(); x.show(); or interface Base, whatever. show() A show() B show() C
  • 41. Topic 4 Duck Typing
  • 42. duck-typing If it looks like a duck and quacks like a duck, it must be a duck. – duck test Quack quack quack! Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object. Won’t rely on inheritance to do polymorph 。
  • 43. duck-typing (cont.) it doesn't actually matter what type my data is - just whether or not I can do what I want with it. if isinstance(myobject, dict):     value = myobject[member] try:      value = myobject[member] except TypeError:     # do something else Not pythonic
  • 44. OK, What’s WRONG about “Just Check type” ? def isExactlyAString(anobj): return type(anobj) is type('') You reject Unicode objects, instances of user-coded subclasses of str, and instances of any user-coded type that is meant to be “string-like” 。 def isStringLike(anobj): try: anobj + '' except: return False else: return True
  • 45. Quick list and dict syntax x = [0,1,2, 3] x[2] list.__getitem__(x, 2) x.__getitem__(2) b = {'a': 0, 'b': 1} b['a'] dict._getitem__(b, 'a') b.__getitem__(‘a’)
  • 46. Duck typing (cont.) x[2] Python don’t care about x’s type 2 If __getitem__ return “quack!” x must be a duck!  if __getitem__ return something meaningless, then an error generaterd.
  • 47. Do you see convenient? myobject = ComplexClass(filename) value = myobject['member 1'] value2 = myobject['member 2'] Python don’t care what type myobject is. As long as myobject.__getitem__(“member 1”) get something useful. You can just use [‘’] dict syntax to do something really complex in your class.
  • 48. Python is TOO DYNAMIC, Can I have a real constants? Any variable can be re-bound in python 。 But…modules don‘t let you do it 。 const.py class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError,”Error!” self.__dict__[name]=value import sys sys.modules[__name__]=_const() import const const.magic = 23 const.magic = 99 (Error!)
  • 49. Topic 5 Some Pattern
  • 50. And… Singleton Pattern? “ Singleton Pattern” ensuring that just one instance of a certain class is ever created. singleton.py: &quot;&quot;&quot;This module implements singleton &quot;&quot;&quot; Python modules are Singleton instances 。 import singleton singleton.XXX Cons: doesn't have a class, can't inherit, and can't be inherited from. It also requires a seperate Python file 。
  • 51. __new__ first step in instance construction, invoked before __init__() 。 return a new instance of that class 。 called with the class as its first argument 。 __init__ () is called with an instance as its first argument, and doesn‘t return anything 。 responsibility of __init__() is to initialize the instance 。
  • 52. Classic Singleton Pattern class Singleton(object): def __new__(type): if not '_instance' in type.__dict__: type._instance=object.__new__(type) return type._instance a=Singleton() b=Singleton() print a==b --> True
  • 53. Python’s Borg Pattern class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state # and whatever else you want in your class -- that's all! Many instances, all share same state. Who cares about *identity* -- it's *state* (and behavior) we care about!
  • 54. For those Getter and setters… okokok, python DO have it… Properties: attributes managed by get/set methods 。 class C(object): def __init__(self): self.__x = 0 def getx(self): return self.__x def setx(self, x): if x < 0: x = 0 self.__x = x x = property(getx, setx) a.x=-10  a.x == 0
  • 55. The Factory pattern? Fact: __init__ can’t return objects. Just use a function to generate objects. Actually…we can even generate a class…
  • 56. inherit in python B(A) => B inherit A means : lookup B attributes(data objects or function objects) that are not found in A 。 Constructor isn’t any special stuff in python 。 A class is ALREADY an object after the class body end 。 (no instance yet)
  • 57. class factory function def class_with_method(func): class klass: pass setattr(klass, func.__name__, func) return klass def say_foo(self): print 'foo' Foo = class_with_method(say_foo) foo = Foo() foo.say_foo() => foo
  • 58. Topic 6 Python is MUCH POWERFUL   than what I introduced, TRY IT yourself.
  • 59. Thank You! Present by Python fans: [email_address] To be continued….

Editor's Notes

  1. 無招勝有招 多型不如無型 重劍無鋒大巧不工
  2. Python don’t need a base “class” to do this… if it walks like a duck and quacks like a duck, it&apos;s duck-like enough for our purposes …