【13】python之面向对象
一、什么是面向对象
面向对象(Object - Oriented):
按人们认识客观世界的系统思维方式,采用基于对象(实体)的概念 建立模型,模拟客观世界分析、设计、实现软件的办法。通过面向对象的理念使计算机软件系统能与现实世界中的系统一一对应。(CSND)
面向对象与面向过程的区别:
面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了;面向对象是把构成问题事务分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描叙某个事物在整个解决问题的步骤中的行为。
四大基本特性:
抽象、封装、继承、多态
二、经典类和新式类
1.类创建不同
Python 2.x中默认都是经典类,只有显式继承了object才是新式类
Python 3.x中默认都是新式类,经典类被移除,不必显式的继承object
2.类继承不同
经典类的实例是通过一个单一的叫做instance的内建类型来实现的,类名和type是无关的,x.__class__定义了x的类名,但是type(x)总是返回<type 'instance'>
新式类都从object继承,type(x)和x.__class__是一样的结果<class 'type'>
3.类基类继承搜索不同
经典类的MRO(method resolution order 基类搜索顺序)算法采用深度优先搜索
新式类的MRO(method resolution order 基类搜索顺序)算法采用C3算法广度优先搜索
class A: pass class B: pass class C(B): pass class D(C,A): pass
继承顺序为:D->C->B,->A
class A(object): pass class B(object): pass class C(object): pass class D(A,B,C): pass
继承顺序为: D->A->B->C->Object
三、类创建
经典类(python3.x中默认均为新式类)
class A(): pass
新式类
class A(object): pass
类的另一种创建方式
def func(self): print("hello %s"%self.name) def __init__(self,name): self.name = name Foo = type('Foo',(object,),{'func':func,'__init__':__init__}) f = Foo("jack") f.func()
四、类继承
class people(object): def __init__(self,name,age): self.name=name self.age=age self.friend=[] def eat(self): print('%s is eating...' %self.name) def talk(self): print('%s is talking...' %self.name) def sleep(self): print('%s is sleeping...' %self.name) class relation(object): # def __init__(self,name): # self.name=name def make_friends(self,obj): print('%s is making friends with %s'%(self.name,obj.name)) self.friend.append(obj) class man(people,relation): def __init__(self,name,age,money): '重构父类构造函数' people.__init__(self,name,age) # super(man,self).__init__(name,age)另一种重构方法 self.money=money def piao(self): print('%s is piaoing...' %self.name) def sleep(self): '重构父类方法' people.sleep(self) print('man is sleeping...' ) class woman(people,relation): def get_birth(self): print('%s is born a baby...' %self.name) m1 = man('m1','25','10') m1.eat() m1.piao() m1.sleep() w1 = woman('w1','25') w1.get_birth() m1.make_friends(w1) print(m1.friend[0].name)
五、类多态
#一个接口,多种形态 class Animal(object): def __init__(self, name): # Constructor of the class self.name = name @staticmethod def func(obj): #多态 obj.talk() class Cat(Animal): def talk(self): print('%s: 喵喵喵!' % self.name) class Dog(Animal): def talk(self): print('%s: 汪!汪!汪!' % self.name) c1 = Cat('c1') d1 = Dog('d1') Animal.func(c1) Animal.func(d1)