Python学习笔记(五)——面向对象编程

1 一个简单的例子

1
2
3
4
5
6
7
8
9
10
11
12
class PartyAnimal:
x = 0

def party(self) : # 第一个参数总是“self”,其它参数放在“self”后面
self.x = self.x + 1
print "So far",self.x

an = PartyAnimal() # 构造一个PartyAnimal实例

an.party()
an.party()
an.party()

程序运行结果:

1
2
3
So far 1
So far 2
So far 3

:类的方法的第一个参数总是“self”,其它参数放在“self”后面

2 dir() 与 type()

例:

1
2
3
4
5
6
7
8
9
10
11
class PartyAnimal:
x = 0

def party(self) :
self.x = self.x + 1
print "So far",self.x

an = PartyAnimal()

print "Type", type(an)
print "Dir ", dir(an)

程序运行结果:

1
2
Type <type 'instance'>
Dir ['__doc__', '__module__', 'party', 'x']

3 对象的生命周期(Object Lifecycle)^1

3.1 构造函数和析构函数

构造函数(Constructors):在实例创建的时候调用,经常用来初始化成员变量(构造函数用得
析构函数(Destructors):在实例被销毁的时候调用(析构函数用得
例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class PartyAnimal:
x = 0

def __init__(self):
print "I am constructed"

def party(self) :
self.x = self.x + 1
print "So far",self.x

def __del__(self):
print "I am destructed",self.x

an = PartyAnimal()
an.party()
an.party()
an.party()

程序运行结果:

1
2
3
4
5
I am constructed
So far 1
So far 2
So far 3
I am destructed 3

3.2 一个类的多个实例

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class PartyAnimal:
x = 0
name = ""
def __init__(self, nam):
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")
s.party()

j = PartyAnimal("Jim")
j.party()
s.party()

程序运行结果:

1
2
3
4
5
Sally constructed
Sally party count 1
Jim constructed
Jim party count 1
Sally party count 2

4 继承(Inheritance)^2

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class PartyAnimal:
x = 0
name = ""
def __init__(self, nam):
self.name = nam
print self.name,"constructed"

def party(self) :
self.x = self.x + 1
print self.name,"party count",self.x

class FootballFan(PartyAnimal): # FootballFan是PartyAnimal的子类
points = 0
def touchdown(self):
self.points = self.points + 7
self.party()
print self.name,"points",self.points

s = PartyAnimal("Sally")
s.party()

j = FootballFan("Jim")
j.party()
j.touchdown()

程序运行结果:

1
2
3
4
5
6
Sally constructed
Sally party count 1
Jim constructed
Jim party count 1
Jim party count 2
Jim points 7

子类可以继承父类的构造函数和所有成员变量和成员方法

https://zh.wikipedia.org/wiki/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1
构造函数:https://zh.wikipedia.org/wiki/%E6%9E%84%E9%80%A0%E5%99%A8