知识点
Python3 面向对象
Python从设计之初就已是一门面向对象的语言,正由于如此,在Python中建立一个类和对象是很容易的。本章节咱们将详细介绍Python的面向对象编程。python
若是你之前没有接触过面向对象的编程语言,那你可能须要先了解一些面向对象语言的一些基本特征,在头脑里头造成一个基本的面向对象的概念,这样有助于你更容易的学习Python的面向对象编程。编程
接下来咱们先来简单的了解下面向对象的一些基本特征。数据结构
面向对象技术简介
类(Class): 用来描述具备相同的属性和方法的对象的集合。它定义了该集合中每一个对象所共有的属性和方法。对象是类的实例。编程语言
方法:类中定义的函数。ide
类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体以外。类变量一般不做为实例变量使用。函数
实例变量:定义在方法中的变量,只做用于当前实例的类。学习
数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。ui
方法重写:若是从父类继承的方法不能知足子类的需求,能够对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。url
继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也容许把一个派生类的对象做为一个基类对象对待。.net
实例化:建立一个类的实例,类的具体对象。
对象:经过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
和其它编程语言相比,Python 在尽量不增长新的语法和语义的状况下加入了类机制。
Python中的类提供了面向对象编程的全部基本功能:类的继承机制容许多个基类,派生类能够覆盖基类中的任何方法,方法中能够调用基类中的同名方法。
对象能够包含任意数量和类型的数据。
类定义
语法格式以下:
class ClassName:
<statement-1>
.
.
.
<statement-N>
1
2
3
4
5
6
类实例化后,可使用其属性,实际上,建立一个类以后,能够经过类名访问其属性。
类对象
类对象支持两种操做:属性引用和实例化。
属性引用使用和 Python 中全部的属性引用同样的标准语法:obj.name。
类对象建立后,类命名空间中全部的命名都是有效属性名。因此若是类定义是这样:
# 一个简单的类实例
class Myclass:
# 属性:
i = 12345
# 方法:
def f(self):
return 'hello world'
# 实例化类
x = Myclass()
# 访问
print('Myclass 类的属性 i 为:',x.i)
print('Myclass 类的方法 f 输出为:',x.f())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
以上建立了一个新的类实例并将该对象赋给局部变量 x,x 为空的对象。
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
Myclass 类的属性 i 为: 12345
Myclass 类的方法 f 输出为: hello world
1
2
3
4
5
不少类都倾向于将对象建立为有初始状态的。所以类可能会定义一个__int__()的特殊方法(构造方法),像下面这样:
def __init__(self):
self.data = []
1
2
类定义了__init__()方法的话,类的实例化操做会自动调用__init()方法。因此在下例中,能够建立一个新的实例:
x = Myclass()
1
固然, __init__() 方法能够有参数,参数经过 __init__() 传递到类的实例化操做上。例如:
class Complex:
def __init__(self,realpart,imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r,x.i)
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
3.0 -4.5
1
2
3
4
5
6
7
8
9
10
11
12
13
self表明类的实例,而非类
类的方法与普通的函数只有一个特别的区别:
它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
<__main__.Test object at 0x00000014F5E029E8>
<class '__main__.Test'>
1
2
3
4
5
6
7
8
9
10
11
12
从执行结果能够很明显的看出,self表明的是类的实例,表明当前对象的地址,而self.__class__则指向类。
self不是python关键字,把他换成其余关键字也是能够正常执行的:
class Test:
def prt(zz):
print(zz)
print(zz.__class__)
t = Test()
t.prt()
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
<__main__.Test object at 0x000000C5A4402978>
<class '__main__.Test'>
1
2
3
4
5
6
7
8
9
10
11
12
类的方法
在类的内部,使用def关键字来定义一个方法,与通常函数定义不一样,类方法必须包含参数self,且为第一个参数,self表明的是类的实例。
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))
# 实例化类1
p = People('小明',10,30)
p.speak()
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
小明 说:我 10 岁。
# 实例化类2
p = People('小明',10)
p.speak()
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
Traceback (most recent call last):
File "D:/untitled/Python_learn/test1.py", line 16, in <module>
p = People('小明',10)
TypeError: __init__() missing 1 required positional argument: 'w'
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
继承
Python一样支持类的继承,若是一种语言不支持继承,类就没有什么意义。派生类的定义以下所示:
class DerivedClassName(BaseClassName1):
<statement-1>
.
.
.
<statement-N>
1
2
3
4
5
6
须要注意圆括号中基类的顺序,如果基类中有相同的方法名,而在子类使用时未指定,Python从左至右搜索,即方法在子类中未找到时,从左到右查找基类中是否包含方法。
BaseClassName(示例中的基类名)必须与派生类定义在一个做用域内。除了类,还能够用表达式,基类定义在另外一个模块中时这一点很是有用:
class DerivedClassName(modname.BaseClassName)
1
# 类定义
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('小明',10,60,3)
s.speak()
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
小明 说:我 10 岁,我在读 3 年级
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
多继承
Python一样有限的支持多继承形式。多继承的类定义以下例:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
1
2
3
4
5
6
须要注意圆括号中父类的顺序,如果父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法。
# 类定义
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))
# 另外一个类,多继承以前的准备
class Speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))
# 多重继承
class Sample(Speaker,Student):
a = ''
def __init__(self,n,a,w,g,t):
Student.__init__(self,n,a,w,g)
Speaker.__init__(self,n,t)
test = Sample('小明',25,80,4,'Python')
test.speak() #方法名相同,默认调用的是在括号中排前的父类的方法
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
我叫 小明,我是一个演说家,我演讲的主题是 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
方法重写
若是你的父类方法的功能不能知足你的需求,你能够在子类重写你父类的方法,实例以下:
# 定义父类
class Parent:
def mymethod(self):
print('我是父类方法')
# 定义子类
class Child(Parent):
def mymethod(self):
print('我是子类方法')
# 子类实例化
c = Child()
# 子类调用重写方法
c.mymethod()
# 用子类对象调用父类已被覆盖的方法
super(Child,c).mymethod() #super() 函数是用于调用父类(超类)的一个方法。
===输出结果===
D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.py
我是子类方法
我是父类方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
类属性与方法
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类地外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
类的方法
在类地内部,使用 def 关键字来定义一个方法,与通常函数定义不一样,类方法必须包含参数 self,且为第一个参数,self 表明的是类的实例。
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类地外部调用。self.__private_methods
类的私有属性示例以下
class JustCounter:
__secretCount = 0 # 私有属性
publicCount = 0 # 公开属性
def count(self):
self.__secretCount += 1
self.publicCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.publicCount)
print(counter.__secretCount) #报错,实例不能访问私有变量
===输出结果===
1
2
2
Traceback (most recent call last):
File "D:/untitled/Python_learn/test1.py", line 18, in <module>
print(counter.__secretCount) #报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
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
类的私有方法示例以下
class Site:
def __init__(self,name,url):
self.name = name #public
self.__url = url #private
def who(self):
print('name : ',self.name)
print('url :',self.__url)
def __foo(self): #私有方法
print('这是私有方法')
def foo(self): #公有方法
print('这是公有方法')
self.__foo()
x = Site('个人博客','https://blog.csdn.net/wanbin6470398/')
x.who()
===输出结果===
name : 个人博客
url : https://blog.csdn.net/wanbin6470398/
x.foo()
===输出结果===
这是公有方法
这是私有方法
x.__foo()
===输出结果===
Traceback (most recent call last):
File "D:/untitled/Python_learn/test1.py", line 21, in <module>
x.__foo()
AttributeError: 'Site' object has no attribute '__foo'
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
类的专有方法
__init__ : 构造函数,在生成对象时调用
__del__ : 析构函数,释放对象时使用
__repr__: 打印,转换
__setitem__ : 按照索引赋值
__getitem__: 按照索引获取值
__len__: 得到长度
__cmp__: 比较运算
__call__: 函数调用
__add__: 加运算
__sub__: 减运算
__mul__: 乘运算
__div__: 除运算
__mod__: 求余运算
__pow__: 乘方
运算符重载
Python一样支持运算符重载,咱们能够对类的专有方法进行重载,示例以下:
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)
===输出结果===D:\untitled\venv\Scripts\python.exe D:/untitled/Python_learn/test1.pyVector(7,8)