11.面向对象

在本节将讲解有关Python3面向对象的有关知识

一、实验目的

  • 继承
  • 方法重写
  • 对象
  • 属性

二、知识要点

1.类

用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。
类的语法格式为:

1
2
3
4
5
6
class ClassName:
<statement-1>
.
.
.
<statement-N>

1.1 类的对象
对象是通过类定义的数据结构实例,类对象支持两种操作:

  • 属性引用
  • 实例化

当创建了一个类的实例即类的具体对象称为类的实例化,类实例化后,可以使用其属性,实际上,创建一个类之后可以通过类名访问其属性,属性引用使用和Python中所有的属性引用一样的标准语法:obj.name,类对象创建后,类命名空间中所有的命名都是有效属性名。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 类的实例化与引用
class MyClass:
i = 12345

def f(self):
return 'hello world'


# 实例化类
x = MyClass()

# 访问类的属性和方法
print("MyClass类的属性i为", x.i)
print("MyClass类的方法f输出为", x.f())

上述代码输出为:
1
2
MyClass类的属性i为 12345
MyClass类的方法f输出为 hello world

1.对象可以包含任意数量和类型的数据。
2.通过del 对象名可以删除对象

类中有一个名为__init__()的特殊方法(构造方法),该方法在类实例化时会自动调用,例如:

1
2
def __init__(self):
self.data = []

即在上面代码中实例化类MyClass时,对应的__init__()方法就会调用,即类定义了__init()方法,类的实例化操作会自动调用__init__()方法。当然__init__()方法也可以有参数,参数通过该方法传递到类的实例化操作上。
例如:
1
2
3
4
5
6
7
8
9
10
# __init__()
class NewClass:
def __init__(self, name, age):
self.n = name
self.a = age


cat = NewClass('zhe', 22)

print(cat.n, cat.a)

输出为:zhe 22

Self代表类的实例,而非类

类的方法与普通函数只有一个特别的区别——他们必须有一个额外的第一个参数名称,按照惯例它的名称为self:
1
2
3
4
5
6
7
8
class Test:
def prt(self):
print(self)
print(self.__class__)


t = Test()
t.prt()

输出为:
1
2
<__main__.Test object at 0x00000285BECB63A0>
<class '__main__.Test'>

从执行结果可以看出self代表的是类的实例,代表当前对象的地址,而self.__class__指向类。self不是python的关键字,把他换成其他名称也是可以执行的。

类变量、实例变量、局部变量、全局变量

类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
局部变量:定义在方法中的变量,只作用于当前实例的类。
实例变量:在类的声明中,属性是用变量来表示的,这种变量就称为实例变量,实例变量就是一个用 self 修饰的变量。
全局变量:在任何位置都能直接使用的变量。

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
global_a = 3  # 全局变量


class VaClass:
class_a = 2 # 类变量

def __init__(self, eg_a):
self.a = eg_a # 实例变量
area_a = 1 # 局部变量
print(area_a, end=",")


a = VaClass(4)
print("{},{},{}".format(global_a, a.a, VaClass.class_a))

最终输出为:1,3,4,2,上述例子只是一个基础用法,有关四个变量的详细解释在之后的文章会写到。

1.2 类的方法
类中定义的函数即称为类的方法。在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例,self不是Python的关键词,可以用其他名称代替。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class my_people:
# 定义基本属性
name = ''
age = 0
# 定义私有属性
__tall = 10

# 定义构造方法
def __init__(self, n, a, t):
self.name = n
self.age = a
self.__tall = t

def speak(self):
print("%s说,我%d岁" % (self.name, self.age))

# 实例化类
zhe = my_people('zhe', 22, 10)
zhe.speak()

输出为:zhe说,我22岁

  • 类的私有方法:

__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用,不能在类的外部调用,调用方法:self.__private_method,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class zoo:
def __init__(self, d, m):
self.dog = d
self.cat = m

def dogspeak(self): # 公共方法
print(self.dog)

def __catspeak(self): # 私有方法
print(self.cat)
def animas(self):
self.__catspeak()
ani = zoo("wang","miao")
ani.dogspeak()
ani.animas()
ani.__catspeak()

输出为:
1
2
3
4
5
6
wang
miao
Traceback (most recent call last):
File "F:/Python/11/eg 11-2.py", line 35, in <module>
ani.__catspeak()
AttributeError: 'zoo' object has no attribute '__catspeak'

可以看出在类外是无法访问私有方法的。

  • 类的专有方法
    __init__ : 构造函数,在生成对象时调用
    __del__: 析构函数,释放对象时使用
    __repr__: 打印,转换
    __setitem__ : 按照索引赋值
    __getitem__: 按照索引获取值
    __len__: 获得长度
    __cmp__: 比较运算
    __call__: 函数调用
    __add__: 加运算
    __sub__: 减运算
    __mul__: 乘运算
    __truediv__: 除运算
    __mod__: 求余运算
    __pow__: 乘方

1.3 类的属性

  • 类的私有属性:

__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问,在类内部的方法使用是self.__private_attr,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class car_m:
__count = 0
wheel = 0
name = ''

def __init__(self, c, w, n):
self.__count = c
self.wheel = w
self.name = n
print(self.__count)


C = car_m(2, 4, 'kdlk')
print(C.wheel)
print(C.__count)

输出结果为:
1
2
3
4
5
6
2
4
Traceback (most recent call last):
File "F:/Python/11/eg 11-2.py", line 16, in <module>
print(C.__count)
AttributeError: 'car_m' object has no attribute '__count'

可见实例化后的对象是无法访问私有属性的,但是在内部类中是可以调用的。

2 继承

2.1 单继承

即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如下图中,Dog类型和Cat类型的对象可派生自Animal类。

stateDiagram
Animal --> Dog
Animal --> Cat

派生类的定义如下所示:

1
2
3
4
5
6
class DerivedClassName(BaseClassName1):
<statement-1>
.
.
.
<statement-N>

注意圆括号中基类的顺序,若是基类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找基类中是否包含方法。BaseClassName(示例中的基类名)必须与派生类定义在一个作用域内。除了类,还可以用表达式,基类定义在另一个模块中时这一点非常有用:
1
class DerivedClassName(modname.BaseClassName):

例如:
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
class people:
# 定义基本属性
name = ""
age = 0
# 定义私有属性
__weight = 0

# 定义构造方法
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w

def speak(self):
print("%s说:我%d岁" % (self.name, self.age))


# 单继承
class student(people):
grade = ""

def __init__(self, n, a, w, g):
# 调用父类的构造函数
people.__init__(self, n, a, w)
self.grade = g

def speak(self):
print("%s说:我%d岁了,在读%d年级" % (self.name, self.age, self.grade))


# 实例化
s = student('ken', 10, 60, 3)
s.speak()

输出为:
1
ken说:我10岁了,在读3年级

2.2 多继承
多继承即一个子类继承多个父类,例如下图中我既是一个设计师又是一个程序员,那么我可以继承设计师和程序员的特点,即:

stateDiagram
Designer --> Me
Programmer --> Me

例如:

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
class people:
# 定义基本属性
age = 0
name = ""
# 定义私有属性
__weight = 0

# 定义构造方法
def __init__(self, a, n, w):
self.age = a
self.name = n
self.__weight = w

def speak(self):
print("我是%s,体重%d,今年%d岁" % (self.name, self.__weight, self.age))


class Designer(people):
hobby = ''

def __init__(self, a, n, w, h):
people.__init__(self, a, n, w)
self.hobby = h

def speak(self):
print("我是%s,是一个设计师,今年%d岁,爱好%s" % (self.name, self.age, self.hobby))


class Programmer(people):
hobby = ''

def __init__(self, a, n, w, h):
people.__init__(self, a, n, w)
self.hobby = h

def speak(self):
print("我是%s,是一个程序员,今年%d岁,爱好%s" % (self.name, self.age, self.hobby))


# 多继承
class Me(Programmer, Designer):
feature = ''

def __init__(self, a, n, w, h, f):
Programmer.__init__(self, a, n, w, h)
Designer.__init__(self, a, n, w, h)
self.feature = f


me = Me(20, "zhe", 10, 'PS', 'cool')
me.speak()

在这段代码中输出为:
1
我是zhe,是一个程序员,今年20岁,爱好PS

注意:方法名同,默认调用的是在括号中排前地父类的方法

3.方法重写

如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下:

1
2
3
4
5
6
7
8
9
10
11
class Parent:        # 定义父类
def myMethod(self):
print ('调用父类方法')

class Child(Parent): # 定义子类
def myMethod(self):
print ('调用子类方法')

c = Child() # 子类实例
c.myMethod() # 子类调用重写方法
super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法

输出为:
1
2
调用子类方法
调用父类方法

super() 函数是用于调用父类(超类)的一个方法,是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题,MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

super()函数:
基本语法:

1
super(type[, object-or-type])

  • type — 类。
  • object-or-type — 类,一般是 self

Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx ,例如:

1
2
3
4
5
6
7
8
9
class A:
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super().add(x)
b = B()
b.add(2) # 3

而Python 2.x需要:
1
2
3
4
5
6
7
8
9
class A(object):   # Python2.x 记得继承 object
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super(B, self).add(x)
b = B()
b.add(2) # 3

三、实验内容

1.运算符重载

使用数量+通过运算符重载实现向量+

  • 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b

def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
  • 结果:
1
Vector (7, 8)

四、实验结果

1.银行账号

我们要确保没人能设置金额为负,并且有个只读属性 cny 返回换算人民币后的金额。

  • 代码
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
#!/usr/bin/env python3

class Account(object):
"""账号类,
amount 是美元金额.
"""
def __init__(self, rate):
self.__amt = 0
self.rate = rate

@property
def amount(self):
"""账号余额(美元)"""
return self.__amt

@property
def cny(self):
"""账号余额(人民币)"""
return self.__amt * self.rate

@amount.setter
def amount(self, value):
if value < 0:
print("Sorry, no negative amount in the account.")
return
self.__amt = value

if __name__ == '__main__':
acc = Account(rate=6.6)
acc.amount = 20
print("Dollar amount:", acc.amount)
print("In CNY:", acc.cny)
acc.amount = -100
print("Dollar amount:", acc.amount)
  • 结果:
1
2
3
4
Dollar amount: 20
In CNY: 132.0
Sorry, no negative amount in the account.
Dollar amount: 20

拓展:property()函数
property() 函数的作用是在新式类中返回属性值。基本语法为:

1
class property([fget[, fset[, fdel[, doc]]]])

其中:

  • fget — 获取属性值的函数
  • fset — 设置属性值的函数
  • fdel — 删除属性值函数
  • doc — 属性描述信息

返回值为新式属性,例如定义一个可控属性值x:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class C(object):
def __init__(self):
self._x = None

def getx(self):
return self._x

def setx(self, value):
self._x = value

def delx(self):
del self._x

x = property(getx, setx, delx, "I'm the 'x' property.")

如果将类C实例化为c,则:
1
2
3
4
c = C()
print(c.x) # 触发setter
c.x = 5 # 触发getter
del c.x # 触发deleter

将property作装饰器@property可以更方便的创建只读属性,有关装饰器的知识将在实验15中提及。


下一篇:12.模块
上一篇:10.异常
目 录:Python学习

本文标题:11.面向对象

文章作者:小哲

发布时间:2020年03月13日 - 23:23

最后更新:2020年03月30日 - 11:40

原始链接: 点击复制原始链接

许可协议: 协议-转载请保留原文链接及作者