7.1 The magic of the object
Polymorphic objects of different classes use the same action
Packaging
Inherited
7.1.1 Polymorphism
1. Polymorphism and methods
>>>object.getprice ()
>>> ' abc '. COUNT (' a ')
1
>>> [, ' A '].count (' a ')
1
>>> from random import choice
>>> x=choice ([' Hello world! ', [Up, ' e ', ' e ', 4]])
>>> x.count (' e ')
1
>>> x=choice ([' Hello world! ', [Up, ' e ', ' e ', 4]])
>>> x.count (' e ')
2
Python polymorphism does not require type detection, as long as there is the same method, Python polymorphism is actually a bit like the Java function overload
>>> def add (x, y):
... return x + y
...
>>> add
3
>>> Add (' Fish ', ' License ')
' Fishlicense '
>>> def length_message (x):
... print "The length of", repr (x), "is", Len (x)
...
>>> length_message (' Fnord ')
The length of ' Fnord ' is 5
>>> length_message ([+])
The length of [1, 2, 3] is 3
Many of the system functions and operators are polymorphic
The only way to destroy polymorphism is to use function display to do type detection, such as type,isinstance, Issubclass, but try to avoid eliminating
7.1.2 Package
7.1.2 Inheritance
7.2 Classes and types
What exactly is the 7.2.1 class?
7.2.2 to create your own class
Class Person:
def setName (self,name):
Self.name=name
def getName (self):
Return Self.name
def greet (self):
Print "Hello world! I ' m%s "% Self.name
>>> Foo=person ()
>>> Bar=person ()
>>> foo.setname (' Luke Skywalker ')
>>> bar.setname (' Anakin skywaler ')
>>> Foo.greet ()
Hello world! I ' m Luke Skywalker
>>> Bar.greet ()
Hello world! I ' m Anakin skywaler
Self represents a reference to the object itself
>>> Foo.name
' Luke Skywalker '
>>> Bar.name
' Anakin Skywaler '
>>> bar.name= ' Yoda '
>>> Bar.greet ()
Hello world! I ' m Yoda
7.2.3 Properties, functions, and methods
This article from "Small Fish Blog" blog, declined reprint!
Reading notes-The second edition of the basic Python tutorial-the seventh chapter is more abstract