Python面向对象
[TOC]
面向对象技术简介
类(Class)
: 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
方法
:类中定义的函数。
类变量
:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
数据成员
:类变量或者实例变量用于处理类及其实例对象的相关的数据。
方法重写
:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
局部变量
:定义在方法中的变量,只作用于当前实例的类。
实例变量
:在类的声明中,属性是用变量来表示的,这种变量就称为实例变量,实例变量就是一个用 self 修饰的变量。
继承
:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟”是一个(is-a)”关系(例图,Dog是一个Animal)。
实例化
:创建一个类的实例,类的具体对象。
对象
:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
和其它编程语言相比,Python 在尽可能不增加新的语法和语义的情况下加入了类机制。
Python中的类提供了面向对象编程的所有基本功能:类的继承机制允许多个基类,派生类可以覆盖基类中的任何方法,方法中可以调用基类中的同名方法。
对象可以包含任意数量和类型的数据。
类定义
语法如下:
1 2 3 4 5 6
| class ClassName: <statement-1> . . . <statement-N>
|
类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性。
类对象
类对象支持两种操作:属性引用和实例化。
属性引用使用和 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())
|
以上创建了一个新的类实例并将该对象赋给局部变量 x,x 为空的对象。
执行以上程序输出结果为:
1 2
| MyClass 类的属性 i 为: 12345 MyClass 类的方法 f 输出为: hello world
|
类有一个名为 __init__()
的特殊方法(构造方法),该方法在类实例化时会自动调用,像下面这样:
1 2
| def __init__(self): self.data = []
|
类定义了 __init__()
方法,类的实例化操作会自动调用 __init__()
方法。如下实例化类 MyClass,对应的 __init__()
方法就会被调用:
当然, __init__()
方法可以有参数,参数通过 __init__()
传递到类的实例化操作上。例如:
1 2 3 4 5 6 7 8
| class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print(x.r, x.i)
|
self代表类的实例,而非类
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。
1 2 3 4 5 6 7
| class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt()
|
执行结果:
1 2
| <__main__.Test instance at 0x100771878> __main__.Test
|
从执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。
self 不是 python 关键字,我们把他换成 hibiscidai 也是可以正常执行的:
1 2 3 4 5 6 7
| class Test: def prt(hibiscidai): print(hibiscidai) print(hibiscidai.__class__) t = Test() t.prt()
|
执行结果:
1 2
| <__main__.Test instance at 0x100771878> __main__.Test
|
类的方法
在类的内部,使用 def
关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
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))
p = people('hibiscidai',10,30) p.speak()
|
执行结果:
继承
Python 同样支持类的继承,如果一种语言不支持继承,类就没有什么意义。派生类的定义如下所示:
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 34 35 36 37
|
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 岁,体重 %d 斤" % (self.name, self.age, self._weight))
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('DJ', 10, 60, 3) s.speak()
|
print1输出:
print2输出:
1 2 3 4 5 6
| Traceback (most recent call last): File "F:/untitled/类定义.py", line 35, in <module> s.speak() File "F:/untitled/类定义.py", line 32, in speak print("%s 说:我 %d 岁了,体重 %d 斤,我在读 %d 年级"%(self.name, self.age, self.__weight, self.grade)) # print2 AttributeError: 'student' object has no attribute '_student__weight'
|
多继承
Python同样有限的支持多继承形式。多继承的类定义形如下例:
1 2 3 4 5 6
| class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N>
|
需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,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
|
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, f): self.name = n self.topic = tuple
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("Tim", 25, 80, 4, "python") test.speak()
|
方法输出结果:
1
| 我叫 Tim,我是一个演说家,我演讲的主题是 Python
|
方法重写
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Parent: def myMethod(self): print ('调用父类方法') class Child(Parent): def myMethod(self): print ('调用子类方法') c = Child() c.myMethod() super(Child,c).myMethod()
|
super()
函数是用于调用父类(超类)的一个方法。
执行以上程序输出结果为:
super()函数
描述
super()
函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
构造方法类似于类似 init() 这种初始化方法,来初始化新创建对象的状态,在一个对象呗创建以后会立即调用。
构造方法中的初始值无法继承问题
案例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print 'Ahahahah' else: print 'No thanks!'
class SongBird(Bird): def __init__(self): self.sound = 'Squawk' def sing(self): print self.song()
sb = SongBird() sb.sing() sb.eat()
|
1.调用未绑定的超类构造方法
1 2 3 4 5 6
| class SongBird(Bird): def __init__(self): Bird.__init__(self) self.sound = 'Squawk' def sing(self): print self.song()
|
在调用了一个实例的方法时,该方法的self参数会自动绑定到实例上(称为绑定方法);如果直接调用类的方法(比如Bird.init),那么就没有实例会被绑定,可以自由提供需要的self参数(未绑定方法)。
2.使用spuer方法
1 2 3 4 5 6
| class SongBird(Bird): def __init__(self): super(SongBird,self).__init__() self.sound = 'Squawk' def sing(self): print self.song()
|
原理:它会查找所有的超类,以及超类的超类,直到找到所需的特性为止。
语法
以下是 super() 方法的语法:
1
| super(type[, object-or-type])
|
参数
- type — 类。
- object-or-type — 类,一般是 self
Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx
代替 super(Class, self).xxx
:
Python3.x 实例:
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)
|
Python2.x 实例:
1 2 3 4 5 6 7 8 9 10 11 12
|
class A(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)
|
返回值
无。
实例
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
|
class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print('Parent')
def bar(self, message): print("%s from Parent" % message)
class FooChild(FooParent): def __init__(self): super().__init__() print('Child')
def bar(self, message): super().bar(message) print('Child bar fuction') print(self.parent)
if __name__ == '__main__': fooChild = FooChild() fooChild.bar('HelloWorld')
|
1 2 3 4 5
| Parent Child HelloWorld from Parent Child bar fuction I'm the parent.
|
先创建父类对象然后再创建子类对象。
调用子类bar()方法,第一步调用父类方法,第二步输出“Child bar fuction”,第三步输出“I’m the parent.”。
经典的菱形继承案例
BC 继承 A,然后 D 继承 BC,创造一个 D 的对象。
1 2 3 4
| graph LR A[A] --> B[B] --> D[D] A[A] --> C[C] --> D[D] F[经典的菱形继承案例]
|
使用 super() 可以很好地避免构造函数被调用两次。
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
| class A(): def __init__(self): print('enter A') print('leave A')
class B(A): def __init__(self): print('enter B') super().__init__() print('leave B')
class C(A): def __init__(self): print('enter C') super().__init__() print('leave C')
class D(B, C): def __init__(self): print('enter D') super().__init__() print('leave D')
d = D()
|
执行结果:
1 2 3 4 5 6 7 8
| enter D enter B enter C enter A leave A leave C leave B leave D
|
新建D对象,执行init方法,先输出“enter D”,然后搜索D类的父类,查看构造函数D继承B,C。
从左到右依次加载BC,进入B创建对象,然后进入C创建对象,然后分别搜索BC父类,可以避免重复加载。
然后依次执行即可。
子类继承父类构造函数说明
如果在子类中需要父类的构造方法就需要显式地调用父类的构造方法,或者不重写父类的构造方法。
- 子类不重写
__init__
,实例化子类时,会自动调用父类定义的 __init__
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Father(object): def __init__(self, name): self.name=name print ( "name: %s" %( self.name) ) def getName(self): return 'Father ' + self.name class Son(Father): def getName(self): return 'Son '+self.name if __name__=='__main__': son=Son('hibiscidai') print ( son.getName() )
|
输出结果为:
1 2
| name: hibiscidai Son hibiscidai
|
- 如果重写了
__init__
时,实例化子类,就不会调用父类已经定义的 __init__
,语法格式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Father(object): def __init__(self, name): self.name=name print ( "name: %s" %( self.name) ) def getName(self): return 'Father ' + self.name class Son(Father): def __init__(self, name): print ( "hi" ) self.name = name def getName(self): return 'Son '+self.name if __name__=='__main__': son=Son('hibiscidai') print ( son.getName() )
|
输出结果为:
- 如果重写了init 时,要继承父类的构造方法,可以使用 super 关键字:
1
| super(子类,self).__init__(参数1,参数2,....)
|
还有一种经典写法:
1
| 父类名称.__init__(self,参数1,参数2,...)
|
实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Father(object): def __init__(self, name): self.name=name print ( "name: %s" %( self.name)) def getName(self): return 'Father ' + self.name class Son(Father): def __init__(self, name): super(Son, self).__init__(name) print ("hi") self.name = name def getName(self): return 'Son '+self.name if __name__=='__main__': son=Son('hibiscidai') print ( son.getName() )
|
输出结果为:
1 2 3
| name: hibiscidai hi Son hibiscidai
|
情况一:子类需要自动调用父类的方法:子类不重写init()方法,实例化子类后,会自动调用父类的init()的方法。
情况二:子类不需要自动调用父类的方法:子类重写init()方法,实例化子类后,将不会自动调用父类的init()的方法。
情况三:子类重写init()方法又需要调用父类的方法:使用super关键词。
类属性与方法
类的私有属性
__private_attrs
:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs
。
类的方法
在类的内部,使用 def
关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self
,且为第一个参数,self
代表的是类的实例。
self
的名字并不是规定死的,也可以使用 this
,但是最好还是按照约定是用 self
。
类的私有方法
__private_method
:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods
。
实例
类的私有属性实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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 3 4 5 6 7
| 1 2 2 Traceback (most recent call last): File "test.py", line 16, 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
|
class Site: def __init__(self, name, url): self.name = name self.__url = url
def who(self): print('name : ', self.name) print('url : ', self.__url)
def __foo(self): print('这是私有方法')
def foo(self): print('这是公共方法') self.__foo()
x = Site('hibiscidai', 'www.hibiscidai.com') x.who() x.foo() x.__foo()
|
1 2 3 4 5 6 7 8 9
| F:\untitled\venv\Scripts\python.exe F:/untitled/私有方法.py Traceback (most recent call last): File "F:/untitled/私有方法.py", line 23, in <module> x.__foo() # 报错 AttributeError: 'Site' object has no attribute '__foo' name : hibiscidai url : www.hibiscidai.com 这是公共方法 这是私有方法
|
类的专有方法
__init__
: 构造函数,在生成对象时调用
__str__
:字符串函数,
__del__
: 析构函数,释放对象时使用
__repr__
: 打印,转换
__setitem__
: 按照索引赋值
__getitem__
: 按照索引获取值
__len__
: 获得长度
__cmp__
: 比较运算
__call__
: 函数调用
__add__
: 加运算
__sub__
: 减运算
__mul__
: 乘运算
__truediv__
: 除运算
__mod__
: 求余运算
__pow__
: 乘方
运算符重载
Python同样支持运算符重载,我们可以对类的专有方法进行重载,实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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)
|
代码执行结果如下