您的位置:首页 > 编程语言 > Python开发

Python(面向对象)

2017-11-27 20:14 218 查看
一、UML

面向对象主要用于软件开发的分析和设计阶段,通常使用UML(统一建模语言)进行建模

统一建模语言并不是软件开发的方法,而是一种描述软件开发过程的图形化标记,UML使用若干种模型来描述软件中开发中的每个重要步骤。

(1)类图(ClassDiagram)。展现了一组对象、接口、协作和它们之间的关系。类图描述的是一种静态关系,在系统的整个生命周期都是有效的,是面向对象系统的建模中最常见的图。

(2)对象图(ObjectDiagram)。展现了一组对象以及它们之间的关系。对象图是类图的实例,几乎使用与类图完全相同的标示。

(3)用例图(UseCaseDiagram)。展现了一组用例、参与者(actor)以及它们之间的关系。用例图从用户角度描述系统的静态使用情况,用于建立需求模型。

(4)交互图。用于描述对象间的交互关系,由一组对象和它们之间的关系组成,包含它们之间可能传递的消息。交互图又分为序列图和协作图,其中序列图描述了以时间顺序组织的对象之间的交互活动;协作图强调收发消息的对象的结构组织。

(5)状态图(StateDiagram)。由状态、转换、事件和活动组成,描述类的对象所有可能的状态以及事件发生时的转移条件。通常状态图是对类图的补充,仅需为那些有多个状态的、行为随外界环境而改变的类画状态图。

(6)活动图(ActiveDiagram)。一种特殊的状态图,展现了系统内一个活动到另一个活动的流程。活动图有利于识别并行活动。

(7)组件图(ComponentDiagram)。展现了一组组件的物理结构和组件之间的依赖关系。部件图有助于分析和理解组件之间的相互影响程度。

(8)部署图(DeploymentDiagram)。展现了运行处理节点以及其中的组件的配置。部署图给出了系统的体系结构和静态实施视图。它与组件图相关,通常一个节点包含一个或多个构建。

二、类和对象

类是一些对象的抽象,隐藏了对象内部复杂的结构和实现。类由变量和函数两部分构成,类中的变量称为成员变量,类中的函数称为成员函数。

类是对客观世界中事物的抽象,而对象是类实例化后的实体。

2.1类的定义

Python使用class关键字定义一个类,类名的首字符一般要大写。类需要把使用的变量和方法组合在一起,这种方法称为封装。

class Fruit:
def __init__(self,name,color):
self.name = name
self.color = color

def grow(self):
print('Friut grow......')
return 0


注意:类的方法必须有1个
4000
self参数,但是在方法调用时,可以不传递这个参数。

2.2对象的创建

创建对象的过程称为实例化,当一个对象被创建后,包含3个方面的特性:对象的句柄、属性和方法,对象的句柄用于区分不同的对象,对象的属性和方法与类的成员变量和成员函数相对应。

if __name__ == "__main__":
friut = Fruit('apple','red')
print(friut.name)
print(friut.color)
print(friut.grow())


Python使用约定属性名称来达到这样数据封装的目的,如果属性的名字以两个下划线开始,就表示私有属性,反之,就表示公有属性。类的方法也这样约定。

Python中静态变量称为类变量,类变量可以在该类的所有实例中被共享,当创建新的实例化对象后,静态变量并不会获得新的内存空间,而是使用类创建的内存空间。

练习(实例变量和类变量的区别):

class Fruit:
price = 0

def __init__(self):
self.color = 'red'
zone = 'China'

if __name__ == "__main__":
print(Fruit.price)
apple = Fruit()
print(apple.color)
Fruit.price = Fruit.price+10
print("apple.price:",str(apple.price))
banana = Fruit()
print("banana.price:",str(banana.price))


class Friut:
def __init__(self):
self.__color = 'red'

if __name__ == "__main__":
apple = Friut()  #实例化类
print(apple._Friut__color)  #通过这样的方式访问类的私有变量


类的内置属性:

class Friut:
def __init__(self):
self.__color = 'red'

class Apple(Friut):
'''this is some of instrction of class'''
pass

if __name__ == "__main__":
fruit = Friut()
apple = Apple()
print('apple.doc',apple.__doc__)
print('apple.dict',apple.__dict__)
print('apple.module',apple.__module__)
print('apple.base',Apple.__bases__)      #Apple类的父类


2.3类的方法

Python使用函数staticmethod()或@staticmethod修饰器把普通函数转换为静态方法,要调用静态方法只需要使用类名作为前缀即可。

class Friut:
price = 0  #类变量
def __init__(self):
self.color = 'red'

def getColor(self):
print(self.color)

# @staticmethod
# def getPrice():
#     print('BEFORE Friut price:',Friut.price)

@staticmethod
def getPrice(cls):
print('BEFORE Friut price:', cls.price)

# def __getPrice(self):
#     Friut.price = Friut.price + 10
#     print('AFTER Friut price:',Friut.price)

def __getPrice(cls):
cls.price = cls.price + 10
print('AFTER Friut price:', cls.price)

count = staticmethod(__getPrice)

if __name__ == "__main__":
apple = Friut()
apple.getColor()

Friut.count(apple)
banana = Friut()
Friut.count(banana)
Friut.getPrice(Friut)


2.4内部类的使用

class Car:
class Door:
def open(self):
print("door open")
class Wheel:
def run(self):
print("car run")
if __name__ == "__main__":
car = Car()
backDoor = Car.Door()
frontDoor = car.Door()
backDoor.open()
frontDoor.open()
wheel = Car.Wheel()
wheel.run()


2.5__init__方法

构造函数用于初始化类的内部状态,为类的属性设置默认值。

class Fruit:
def __init__(self,color):
self.__color = color
print("init.self.color:",self.__color)
def getColor(self):
print("getColor.self.color:",self.__color)

def setColor(self,color):
self.__color = color
print("setColor.self.color:",self.__color)

if __name__ == "__main__":

color = 'red'
fruit = Fruit(color)
fruit.getColor()
color = 'blue'
fruit.setColor(color)


2.6__del__方法

析构函数用于释放对象占用的资源,如果程序中不提供析构函数Python会自动在后台提供默认的析构函数。Python中定义了del()的实例将无法被Python循环垃圾收集器(gc)收集,所以谨慎。

class Fruit:
def __init__(self,color):
self.__color = color
print("init.self.color:",self.__color)

def __del__(self):
self.__color = " "
print("del.self.color:",self.__color)
print("del finish...")

def grow(self):
print("fruit grow...")

if __name__ == "__main__":
color = "red"
apple =Fruit(color)
apple.grow()
del apple


2.7垃圾回收机制

Python采用垃圾回收机制清除对象,Python提供了gc模块释放不再使用的对象,垃圾回收的机制有很多算法,Python采用的时引用计数的方式,当某个对象在其作用域内引用计数为0时,Python会自动清除该对象。

#定义水果类

import gc  #导入垃圾回收模块
class Fruit:
def __init__(self,name,color):  #重写构造函数
self.__name = name    #初始化类的私有变量
self.__color = color

def getName(self): #获取类的私有变量值
return self.__name

def setName(self,name):  #设置类的私有变量值
self.__name = name
print("setName.name:",self.__name)

def getColor(self):
return self.__color

def setColor(self,color):
self.__color = color
print("setColor.color:",self.__color)

class fruitShop:
def __init__(self):   #初始化fruitShop
self.__fruits = []

def getFruit(self):
print(self.__fruits)

def addFruit(self,fruit): #向私有变量中追加列表元素
fruit.parent = self  #设置fruit对象的parent属性为self
self.__fruits.append(fruit)

if __name__ == "__main__":
fruit_shop  = fruitShop()  #实例化fruitShop类
fruit_shop.addFruit(Fruit('apple','red'))  #调用addFruit()
fruit_shop.addFruit(Fruit('banana','yellow'))
print('refer:\n',gc.get_referrers(fruit_shop))  #调用gc.get_referrers()函数获取对象的相关参数
del fruit_shop   #释放对象资源
print('collection:\n',gc.collect())   #获取垃圾回收的相关内容


2.8类的内置方法

(1)new()

实现单例模式,new()在init()之前被调用,用于创建实例对象

#__new__()在__init__()之前被调用
#利用__new__()可以实现单例模式

class singleton(object):
__instance = None

def __init__(self):
pass
def __new__(cls, *args, **kwargs):  #在__init__()之前调用__new__()
if singleton.__instance == None:  #生成唯一实例
singleton.__instance = object.__new__(cls,*args,**kwargs)
return singleton.__instance


(2)getattr()、setattr()和getatrribute()

class Fruit(object):
def __init__(self,color='red',price=0): #初始化类的私有变量
self.__color = color
self.__price = price

def __getattribute__(self,
102ca
name):
return object.__getattribute__(self,name)

def __setattr__(self, key, value):
self.__dict__[key] = value

if __name__ == "__main__":
fruit = Fruit('blue',10)
print(fruit.__dict__.get('_Fruit__color'))  #获取类的color属性
fruit.__dict__['_Fruit__price'] = 20    #设置类的price属性
print(fruit.__dict__.get('_Fruit__price'))   #获取类的price


(3)getitem()

class FruitShop:
def __init__(self):
self.fruits = []

def __getitem__(self, i):  #返回fruits中的每个元素
return self.fruits[i]   #fruits属性被保存至__dict__字典中

if __name__ == "__main__":
shop = FruitShop()
shop.fruits = ['apple','banana']
print(shop[0],shop[1])
print(shop)
for item in shop:
print(item,end=' ')


(4)str()

str()用于表示对象代表的含义,返回一个字符串

class Fruit:
'''Fruit类'''
def __str__(self):
return self.__doc__  #必须用return语句返回,否则print语句会出错

if __name__ == "__main__":
fruit = Fruit()
print(str(fruit))  #通过函数str()触发__str__()的执行
print(fruit)  #直接使用print语句输出对象


(5)call()

在类中实现call()方法,可以在对象创建时直接返回call()的内容

class Fruit:
class Growth:
def __call__(self, *args, **kwargs):  #与静态类函数相似
print('grow...')
grow = Growth()  #调用Growth,将类Growth作为函数返回,即为外部函数定义函数grow()

if __name__ == '__main__':
fruit = Fruit()
fruit.grow()
Fruit.grow()


2.9方法的动态特性

(1)动态添加方法

#动态添加方法
class Fruit:
pass

def add(self):
print('grow')

if __name__ == '__main__':
Fruit.grow = add   #直接用类对象添加方法,之后在实例化出对象
fruit = Fruit()
fruit.grow()


(2)更新方法

class Fruit:
def grow(self):
print('grow...')

def update(self):
print('update...')

if __name__ == "__main__":
fruit = Fruit()
fruit.grow()
Fruit.grow = update  #更新类中的方法
fruit.grow()


三、继承

3.1使用继承

class Fruit:   #定义基类
def __init__(self,color):  #基类的构造函数
self.color = color
print('Fruit.color:',self.color)
def grow(self):
print('Fruit grow...')

class Apple(Fruit):   #派生类继承父类
def __init__(self,color):  #派生类的构造函数
Fruit.__init__(self,color)  #显示调用父类的构造函数
print('Apple.color',self.color)

class Banana(Fruit):
def __init__(self,color):
Fruit.__init__(self,color)
print('Banana.color',self.color)

if __name__ == "__main__":
apple = Apple('red')   #实例化对象
apple.grow()  #调用从父类继承来的grow()函数
banana = Banana('yellow')
banana.grow()


3.2抽象继承

使用集成之后,子类可以重用父类中的属性和方法,并且可以对继承的方法进行重写,抽象基类时对一类事物的特征行为的抽象,由抽象方法组成,抽象基类不能被直接实例化

#定义抽象基类,需导入ABCMeta,abstractmethod

from abc import ABCMeta,abstractmethod

class Fruit(metaclass=ABCMeta):  #继承抽象基类ABCMeta
@abstractmethod  #声明抽象函数
def grow(self):
pass

class Apple(Fruit):  #子类重写抽象函数
def grow(self):
print('APPLE grow..')

if __name__ == "__main__":
apple = Apple()
apple.grow()


3.3多态性

继承机制说明子类具有父类的公有属性和方法,而且子类可以扩展自身的功能,添加新的属性和方法,因此,子类可以代替父类对象,这种特性为多态性。

#实现类之间的多态

class Fruit:   #定义基类并定义构造函数
def __init__(self,color=None):
self.color = color

class Apple(Fruit):  #子类继承父类,并显示调用父类的构造函数
def __init__(self,color):
super(Apple,self).__init__()

class Banana(Fruit):  #子类继承父类,并显示调用父类的构造函数
def __init__(self,color):
super(Banana,self).__init__()

class FruitShop:
def sellFruit(self,fruit):  #判断传入的实例对象属于那个类,针对不同的类实行不同的动作
if isinstance(fruit,Apple):
print('sell apple...')
if isinstance(fruit,Banana):
print('sell banana...')
if isinstance(fruit,Fruit):
print('sell fruit')

if __name__ == "__main__":
apple = Apple('red')
banana = Banana('yellow')
fruit = Fruit('blue')

shop = FruitShop()
shop.sellFruit(apple)
shop.sellFruit(banana)
shop.sellFruit(fruit)


3.4多重继承

#python支持多重继承

class Fruit:
def __init__(self):
print("Fruit.init...")
def grow(self):
print("furit.grow...")
class Veg:
def __init__(self):
print("Veg.init...")
def plant(self):
print("fruit.plant...")

class Melon(Veg,Fruit):   #在继承会继承第一个父类的构造函数
pass

if __name__ == "__main__":
melon = Melon()
melon.grow()
melon.plant()


3.5Mixin机制

Mixin 机制把Fruit类、HuskdFruit类,DecorticateFruit类放在同一个层次,具体的水果类使用多重继承的方式继承所属的分类。

class Fruit(object):
pass

# class HuskedFruit(Fruit):
#     def __init__(self):
#         print("initialize HuskedFruit")
#
#     def husk(self):
#         print("husk...")
#
# class DecorticatedFruit(Fruit):
#     def __init__(self):
#         print("initialize DecorticatedFruit")
#
#     def decorate(self):
#         print("decorate...")
# class Apple(HuskedFruit):
#     pass
#
# class Banana(DecorticatedFruit):
#     pass

#Mixin实现

class HuskedFruit(object):
def __init__(self):
print("initialize HuskedFruit")

def husk(self):
print("husk...")

class DecorticatedFruit(object):
def __init__(self):
print("initialize DecorticatedFruit")

def decorate(self):
print("decorate...")

class Apple(HuskedFruit,Fruit):
pass

class Banana(DecorticatedFruit,Fruit):
pass


3.5运算符重载

加号和大于号符号重载

class Friut:
def __init__(self,price=0):
self.price = price
print("init.self.price:",self.price)

def __add__(self, other):
return self.price+other.price

def __gt__(self, other):
if self.price>other.price:
return True
else:
return False

class Apple(Friut):
pass

class Banana(Friut):
pass

if __name__ == "__main__":
apple = Apple(10)
banana = Banana(20)
total_price = apple+banana
print("total_price:",total_price)

print(apple>banana)


运算符<<的重载

import sys

class Stream:
def __init__(self,file):
self.file = file

def __lshift__(self, obj):
self.file.write(str(obj))
return self

class Fruit(Stream):
def __init__(self,price=0,file=None):
Stream.__init__(self,file)
self.price = price

class Apple(Fruit):
pass
class Banana(Fruit):
pass

if __name__ == "__main__":
apple = Apple(10,sys.stdout)
banana = Banana(20,sys.stdout)

endl = '\n'
apple<<apple.price<<endl
banana<<banana.price<<endl


四、Python实现工厂模式

在工厂模式中,工厂方法用于创建产品,并隐藏了产品对象实例化的过程,工厂方法根据不同的参数生成不同的对象,因此,客户程序只需知道工厂类和产品的父类,并不需要知道产品的创建过程,以及返回的产品类型。

#工厂模式实现

#工厂类,实现产品的生产

class Factory:
def createFruit(self,fruit):
if fruit == "apple":
return Apple()
if fruit == "banana":
return Banana()

class Fruit():
def __str__(self):
return 'Fruit...'

class Apple(Fruit):
def __str__(self):
return 'apple...'

class Banana(Fruit):
def __str__(self):
return 'banana...'

if __name__ == "__main__":
factor = Factory()
print(factor.createFruit('apple'))
print(factor.createFruit('banana'))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息