Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Dynamic Python


Published on

  • Be the first to comment

Dynamic Python

  1. 1. Dynamic Python Think Dynamic [email_address]
  2. 2. Python Advertising <ul><li>What Programmers and enterprise says about using Python. </li></ul><ul><li>Speed/Memory usage when compare Python with other languages. </li></ul>
  3. 3. Master says…. <ul><li>Python Is OOP Done Right </li></ul><ul><ul><ul><ul><ul><li>– “ Programming Python”,21.6.3 </li></ul></ul></ul></ul></ul><ul><li>Perl is worse than Python because people wanted it worse. -- Larry Wall </li></ul><ul><li>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 </li></ul>
  4. 4. Master says….    (cont.) <ul><li>Python ... is compact -- you can hold its entire feature set (and at least a concept index of its libraries) in your head. </li></ul><ul><li>-- Eric S. Raymond </li></ul><ul><li>&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. </li></ul>
  5. 5. Master says…. (cont.) <ul><li>&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 . </li></ul>
  6. 6. Master says…. (cont.) <ul><li>&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 . </li></ul>
  7. 7. all&lang =perl&lang2=python
  8. 8.
  9. 9. all&lang =java&lang2=python
  10. 10.
  11. 11.
  12. 12.
  13. 13. Today’s topic <ul><li>Python doesn't have ‘Char’ type </li></ul><ul><li>- Sequence </li></ul><ul><li>- Slice </li></ul><ul><li>Dynamic Python features – an brief introduction </li></ul><ul><li>- name-based polymorphism </li></ul><ul><li>- Duck typing </li></ul>
  14. 14. One Minute Python Tutorial <ul><li>import os </li></ul><ul><li>def do_func(): </li></ul><ul><ul><li>my_list = ['hello','world', 2 ,'python!'] </li></ul></ul><ul><ul><li>for x in my_list: </li></ul></ul><ul><ul><ul><li>print x, </li></ul></ul></ul><ul><li>a='ls -al' </li></ul><ul><li>if a=='ls -al': </li></ul><ul><ul><li>do_func() </li></ul></ul><ul><li>os.system(a) </li></ul>
  15. 15. Choice – If …..and only if …. <ul><li>if python == quick_enough_for_you: </li></ul><ul><li>python=your_primary_language </li></ul><ul><li>else: </li></ul><ul><li>python=your_glue_language </li></ul><ul><li>Use Indent – NO curly brackets { } </li></ul><ul><li>Some keyword: pass,elif,and,or,not </li></ul><ul><li>No Switch. </li></ul><ul><li>z=b if a<b else z=a (python 2.5,pep308) </li></ul>
  16. 17. Five Minutes Python Deploy Demo <ul><li>Bulid Native Python Program (ELF,EXE) </li></ul><ul><ul><li>, py2exe (win32 only), pyinstaller </li></ul></ul><ul><ul><li>Build python script to windows EXE format on Linux via wine and pyinstaller </li></ul></ul><ul><li>Cross Compile Python via crosspy script. </li></ul><ul><ul><li>Setup a GNU toolchain(binutils,compiler). </li></ul></ul><ul><ul><li>Cross compile Python module is a little harder. </li></ul></ul><ul><ul><li>Python is so SMALL for LOTS features it supply. really... </li></ul></ul>
  17. 18. Topic 1 String, Slice
  18. 19. Python String <ul><li>Python doesn’t have a Char type 。 </li></ul><ul><li> String </li></ul><ul><li>Python String is </li></ul><ul><li>- a object </li></ul><ul><li>- a sequence of characters </li></ul><ul><li>x = “Hello World” </li></ul><ul><li>type(x)  <type ‘str’> </li></ul><ul><li>y = str(“Hello World”) </li></ul>
  19. 20. Manipulate strings (type str) <ul><li>Invoke Python Interpreter </li></ul><ul><li>x = ‘Hell’+’o’ #no plus works too </li></ul><ul><li>x </li></ul><ul><li>‘ ==‘+x*5+’==‘ </li></ul><ul><li>x[3] </li></ul><ul><li>x[0:2] #slice is slight different </li></ul><ul><li>x[:2] # then element access </li></ul>
  20. 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
  21. 22. Manipulate strings (cont.) <ul><li>x[2:] </li></ul><ul><li>x[1:100] #python knows boundary </li></ul><ul><li>x[2:1] #return “”,always [begin:end] </li></ul><ul><li>x[-1] </li></ul><ul><li>x[-2:] </li></ul><ul><li>x[:-2] </li></ul>
  22. 23. Manipulate string (cont.) <ul><li>s = 'supercalifragilisticexpialidocious' len(s) </li></ul><ul><li>'ab' in 'abcd' #return true. </li></ul><ul><li>' abc '.strip()  ’abc’ </li></ul><ul><li>'><><abc<><><>'.strip('<>')  ’abc’ </li></ul><ul><li>'><><abc<><><> '.strip('<>')  same str </li></ul><ul><li>'45'.zfill(4)  ’0045’ </li></ul><ul><li>dir( '' ) ==> help() </li></ul>
  23. 24. Topic 2 List, Sequence, Iterator
  24. 25. List <ul><li>Show = [‘hello’,’world’,1,999] </li></ul><ul><li>Show </li></ul><ul><li>Show[0] </li></ul><ul><li>Show[3] </li></ul><ul><li>Show[3]=Show[3]+255 </li></ul><ul><li>Show[1:3] # slice can work on list  </li></ul><ul><li>Show[:2]+[“wow”,”hey”]+3*show[:1] </li></ul>
  25. 26. Slices advanced. (python 2.3↑) <ul><li>L = range(10) </li></ul><ul><li>L[1:7:2] -- [1,3,5] </li></ul><ul><li>L[::2] -- [0,2,4,6,8] </li></ul><ul><li>L[::-1] -- reverse list </li></ul><ul><li>del L[::2] -- [1,3,5,7,9] </li></ul><ul><li>range(10)[slice(0, 5, 2)] -- [0,2,4] </li></ul><ul><li>range(10).__getitem__(slice(0, 5, 2)) </li></ul>
  26. 27. Sequence <ul><li>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. </li></ul><ul><li>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. </li></ul>
  27. 28. iterator <ul><li>An object representing a stream of data. </li></ul><ul><li>Repeated calls to the iterator's next() method return successive items in the stream. </li></ul><ul><li>When no more data is available a StopIteration exception is raised instead. </li></ul><ul><li>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. </li></ul>
  28. 29. How Java iterate Sequence (Collection, Array) <ul><li>for ( Iterator i = c.iterator(); i.hasNext(); ) { String s = ( String ); </li></ul><ul><li>... </li></ul><ul><li>} </li></ul><ul><li>Java 1.5↑(JSR 201): </li></ul><ul><li>for ( String s : c)  JAVA 1.5 </li></ul><ul><li>{ ... } </li></ul><ul><li>for s in c:  Python </li></ul><ul><ul><li>… </li></ul></ul>
  29. 30. iterable <ul><li>A container object capable of returning its members one at a time. </li></ul><ul><li>for x in range(0, 10): </li></ul><ul><li>print x </li></ul><ul><li>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. </li></ul>
  30. 31. Iterable demo <ul><li>x=[1,2,3] </li></ul><ul><li>iter(x) </li></ul><ul><li>i=x.__iter__() </li></ul><ul><li> </li></ul><ul><li>Implement your __iter__() and next() method then you can get a Iterable </li></ul>
  31. 32. Sequence (summary) <ul><li>A iterable supports indexing, slicing, and being passed to the built-in function len. </li></ul><ul><li>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. </li></ul>
  32. 33. Topic 3 Namespace, Polymorph
  33. 34. A simple question… <ul><li>String foo = “foo”; What is the type of foo? </li></ul><ul><li>Type String ? (type == class) </li></ul><ul><li>String tim; </li></ul><ul><li>tim has type 'String‘. </li></ul><ul><li>tim can only reference objects that are class String…….in C++ & java </li></ul><ul><li>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.) </li></ul>
  34. 35. Namespace <ul><li>Namespaces are one honking great idea -- let's do more of those! – The Zen of Python </li></ul><ul><li>Basic “three-scope rule” (builtin/global/local), (However Python 2.1 add nested scoping) 。 </li></ul><ul><li>x=“Hello World” </li></ul><ul><li>If “Hello World” doesn’t exist, python create it. </li></ul><ul><li>If “Hello World” exist, python locate it. </li></ul><ul><li>x is a name. “Hello World” is a string object. </li></ul>
  35. 36. Namespace (cont.) <ul><li>If the name x doesn’t exist in current namespace, the name x is bound to “Hello World” 。 </li></ul><ul><li>If a name x is exist in current namespace, it is rebound 。 </li></ul><ul><li>Multiple names can bound to same object 。 </li></ul><ul><li>BTW: x = y means dereference y and bound to name x 。 </li></ul>
  36. 37. Python Mind Testing Problem <ul><li>A=1 </li></ul><ul><li>A=“HELLO” </li></ul><ul><li>just changed type ? NO! </li></ul><ul><li>the A itself is not “an object”, it’s a name. </li></ul><ul><li>Create an integer object with the value 1 and bind the name ‘A' to it. </li></ul><ul><li>Then create a new string object with the value HELLO, and rebind the name ‘A' to it. </li></ul>
  37. 38. Python Mind Testing Problem(cont.) <ul><li>Object reference -- name without type. </li></ul><ul><li>Object -- typed. </li></ul><ul><li>Python is dynamically but strongly typed. </li></ul><ul><li>dynamically typed: the reference (“name”) </li></ul><ul><li>strongly typed: objects don't change type </li></ul><ul><li>Historically, &quot;strong typing&quot; has been associated with static typing. </li></ul>
  38. 39. name-based polymorphism . <ul><li>type based polymorphism (C++,Java) </li></ul><ul><li>name-based polymorphism. (smalltalk) </li></ul><ul><li>Python’s “Polymorphism” is NOTHING to do with inheritance. </li></ul><ul><li>As said, Python variables do NOT have a type. </li></ul><ul><li>Python can use one variable to hold any kind of objects. </li></ul>
  39. 40. show() Base x=A() #you can also try this class Base; array = [ A(),B(),C() ] class A extends Base; x=B() for x in array: class B extends Base; class C extends Base; x=C() Base x; x= new B();; or interface Base, whatever. show() A show() B show() C
  40. 41. Topic 4 Duck Typing
  41. 42. duck-typing <ul><li>If it looks like a duck and quacks like a duck, it must be a duck. – duck test </li></ul><ul><li>Quack quack quack! </li></ul><ul><li>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. </li></ul><ul><li>Won’t rely on inheritance to do polymorph 。 </li></ul>
  42. 43. duck-typing (cont.) <ul><li>it doesn't actually matter what type my data is - just whether or not I can do what I want with it. </li></ul><ul><li>if isinstance(myobject, dict):     value = myobject[member] </li></ul><ul><li>try:      value = myobject[member] except TypeError:     # do something else </li></ul>Not pythonic
  43. 44. OK, What’s WRONG about “Just Check type” ? <ul><li>def isExactlyAString(anobj): </li></ul><ul><li>return type(anobj) is type('') </li></ul><ul><li>You reject Unicode objects, </li></ul><ul><li>instances of user-coded subclasses of str, and instances of any user-coded type that is meant to be “string-like” 。 </li></ul><ul><li>def isStringLike(anobj): </li></ul><ul><li>try: anobj + '' </li></ul><ul><li>except: return False </li></ul><ul><li>else: return True </li></ul>
  44. 45. Quick list and dict syntax <ul><li>x = [0,1,2, 3] </li></ul><ul><li>x[2] </li></ul><ul><li>list.__getitem__(x, 2) </li></ul><ul><li>x.__getitem__(2) </li></ul><ul><li>b = {'a': 0, 'b': 1} </li></ul><ul><li>b['a'] </li></ul><ul><li>dict._getitem__(b, 'a') </li></ul><ul><li>b.__getitem__(‘a’) </li></ul>
  45. 46. Duck typing (cont.) <ul><li>x[2] </li></ul><ul><li>Python don’t care about x’s type </li></ul><ul><li>2 </li></ul><ul><li>If __getitem__ return “quack!” x must be a duck!  </li></ul><ul><li>if __getitem__ return something meaningless, then an error generaterd. </li></ul>
  46. 47. Do you see convenient? <ul><li>myobject = ComplexClass(filename) value = myobject['member 1'] value2 = myobject['member 2'] </li></ul><ul><li>Python don’t care what type myobject is. </li></ul><ul><li>As long as myobject.__getitem__(“member 1”) get something useful. </li></ul><ul><li>You can just use [‘’] dict syntax to do something really complex in your class. </li></ul>
  47. 48. Python is TOO DYNAMIC, Can I have a real constants? <ul><li>Any variable can be re-bound in python 。 </li></ul><ul><li>But…modules don‘t let you do it 。 </li></ul><ul><li> </li></ul><ul><li>class _const: </li></ul><ul><li>class ConstError(TypeError): pass </li></ul><ul><li>def __setattr__(self,name,value): </li></ul><ul><li>if self.__dict__.has_key(name): </li></ul><ul><li>raise self.ConstError,”Error!” </li></ul><ul><ul><ul><ul><ul><li>self.__dict__[name]=value </li></ul></ul></ul></ul></ul><ul><li>import sys </li></ul><ul><li>sys.modules[__name__]=_const() </li></ul><ul><li>import const </li></ul><ul><ul><li>const.magic = 23 </li></ul></ul><ul><ul><li>const.magic = 99 (Error!) </li></ul></ul>
  48. 49. Topic 5 Some Pattern
  49. 50. And… Singleton Pattern? <ul><li>“ Singleton Pattern” ensuring that just one instance of a certain class is ever created. </li></ul><ul><li> </li></ul><ul><li>&quot;&quot;&quot;This module implements singleton &quot;&quot;&quot; </li></ul><ul><li>Python modules are Singleton instances 。 </li></ul><ul><li>import singleton </li></ul><ul><li>singleton.XXX </li></ul><ul><li>Cons: doesn't have a class, can't inherit, and can't be inherited from. It also requires a seperate Python file 。 </li></ul>
  50. 51. __new__ <ul><li>first step in instance construction, invoked before __init__() 。 </li></ul><ul><li>return a new instance of that class 。 </li></ul><ul><li>called with the class as its first argument 。 </li></ul><ul><li>__init__ () is called with an instance as its first argument, and doesn‘t return anything 。 </li></ul><ul><li>responsibility of __init__() is to initialize the instance 。 </li></ul>
  51. 52. Classic Singleton Pattern <ul><li>class Singleton(object): </li></ul><ul><li>def __new__(type): </li></ul><ul><li>if not '_instance' in type.__dict__: type._instance=object.__new__(type) </li></ul><ul><li>return type._instance </li></ul><ul><li>a=Singleton() </li></ul><ul><li>b=Singleton() </li></ul><ul><li>print a==b --> True </li></ul>
  52. 53. Python’s Borg Pattern <ul><li>class Borg: </li></ul><ul><li>__shared_state = {} </li></ul><ul><li>def __init__(self): </li></ul><ul><li>self.__dict__ = self.__shared_state </li></ul><ul><li># and whatever else you want in your class -- that's all! </li></ul><ul><li>Many instances, all share same state. </li></ul><ul><li>Who cares about *identity* -- it's *state* (and behavior) we care about! </li></ul>
  53. 54. For those Getter and setters… okokok, python DO have it… <ul><li>Properties: attributes managed by get/set methods 。 </li></ul><ul><li>class C(object): </li></ul><ul><ul><li>def __init__(self): self.__x = 0 </li></ul></ul><ul><ul><li>def getx(self): return self.__x </li></ul></ul><ul><ul><li>def setx(self, x): </li></ul></ul><ul><ul><li> if x < 0: x = 0 </li></ul></ul><ul><ul><li> self.__x = x </li></ul></ul><ul><ul><li>x = property(getx, setx) </li></ul></ul><ul><li>a.x=-10  a.x == 0 </li></ul>
  54. 55. The Factory pattern? <ul><li>Fact: __init__ can’t return objects. </li></ul><ul><li>Just use a function to generate objects. </li></ul><ul><li>Actually…we can even generate a class… </li></ul>
  55. 56. inherit in python <ul><li>B(A) => B inherit A means : </li></ul><ul><li>lookup B attributes(data objects or function objects) that are not found in A 。 </li></ul><ul><li>Constructor isn’t any special stuff in python 。 </li></ul><ul><li>A class is ALREADY an object after the class body end 。 (no instance yet) </li></ul>
  56. 57. class factory function <ul><li>def class_with_method(func): </li></ul><ul><ul><li>class klass: pass </li></ul></ul><ul><ul><li>setattr(klass, func.__name__, func) </li></ul></ul><ul><ul><li>return klass </li></ul></ul><ul><ul><li>def say_foo(self): print 'foo' </li></ul></ul><ul><ul><li>Foo = class_with_method(say_foo) </li></ul></ul><ul><ul><li>foo = Foo() </li></ul></ul><ul><ul><li>foo.say_foo() => foo </li></ul></ul>
  57. 58. Topic 6 Python is MUCH POWERFUL   than what I introduced, TRY IT yourself.
  58. 59. Thank You! Present by Python fans: [email_address] To be continued….