-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter14-object-orientied-python
82 lines (72 loc) · 2.35 KB
/
chapter14-object-orientied-python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# simple python objects
class PartyAnimal: # making a PartyAnimal object # class is a tempalte (dog)
x=0 # each PartyAnimal object has a bit of data
def party(self): # each PartyAnimal object has a bit of code # party() is a method or message like bark(), capability of a class
self.x = self.x + 1
print "So far", self.x
an = PartyAnimal() # a is an object, which contain data (x 0) and code ( party() )
# an is an object or instance, a particular instance of a class - Lassie
an.party() # tell the object to run the party() code, = PartyAnimal.party(a); So far 1
an.party() # So far 2
an.party() # So far 3
# 'self' is a formal argument that refers to the object itself
self.x is saying "x within self"
in this case, self is alias of object an
dir() commend lists capabilities/methods # party(),x
type() # instance
# object lifecycle
class .... :
x=0
def_init_(self):
print"I am constructed" # self an once appreas, execute this # normal
def party(self):
:
:
def_def_(self):
print"I am destructed", self.x # rare
class PartyAnimal:
x=0
name = " "
def_init_(self,nam): # nam is the first parameter
self.name = nam
print self.name, "constructed"
def party(self):
self.x = self.x +1
print self.name, "party count", self.x
s = PartyAnimal("Sally")
----------------------------------------------------------------------------
print(ord(‘H’) ->72, print (ord(‘e’))-> 101, print(ord(‘\n’))->10
ASCII, UTF-8 (Bytes), X=a’bcd’, type(x)->byte : In python3, all strings are Unicode, x=u’你好’, type(x)->str
Class(string), method/message(string.upper), field/attribute, object/instance
class PartyAnimal:
X=0
Name=’’
def _init_(self,z):
self.name=z
print(‘self.name, “constructed”)
def party(self):
self.x=self.x+1
print(self.name, “party count”, self.x)
#def _del_(self):
#print (‘I am destructed’,self.x)
class FootballFan(PartyAnimal): # Objective inheritance
points=0
def touchdown(self):
self.points=self.points+7
self.party()
print(self.name, “points”, self.points)
an=PartyAnimal()
s=PartyAnimal(‘Sally’)
s.party()
j=PartyAnimal(‘Jim’)
j.party()
j=FootballFan(‘Jim’)
j.party()
j.touchdown()
an.party()
an.party()
an.party()
an=42
print (“Type”,’type(an))
print(“Dir”, dir(an))
print(‘an contains’,an)