第8章 面向对象编程

本章知识点:

1、类和对象;
2、属性和方法;
3、继承和组合;
4、类的多态性;
5、类的访问权限;
6、设计模式的应用;

内容:

8.1 面向对象的概念

1、用例图
2、活动图
3、状态图
4、类图
5、序列图和协助图
6、组建图和部署图

8.2 类和对象

8.2.1 类和对象的区别

8.2.2 类的定义

## 继承自object
class Class_name(object):
    ...
## 不显式继承object
class Class_name:
    ...
## 类的创建
class Fruit:
    def __init__(self):
        self.name = name
        self.color = color
    def grow(self):
        print "Fruit grow ..."

8.2.3 对象的创建

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

8.3 属性和方法

8.3.1 类的属性

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's price:" + str(banana.price))
## 访问私有属性
class Fruit:
    def __init__(self):
        self.__color = "red"
if __name__ == "__main__":
    apple = Fruit()
    print (apple._Fruit__color)
# 输出:red
class Fruit:
    def __init__(self):
        self.__color = "red"
class Apple(Fruit):
    """This is doc"""
    pass
if __name__ == "__main__":
    fruit =Fruit()
    apple = Apple()
    print (Apple.__bases__)
    print (apple.__dict__)
    print (apple.__module__)
    print (apple.__doc__)
# 输出:(<class '__main__.Fruit'>,)
# {'_Fruit__color': 'red'}
# __main__
# This is doc

8.3.2 类的方法

class Fruit:
    price = 0
    def __init__(self):
        self.__color = "red"
    def getColor(self):
        print (self.__color)
    @staticmethod
    def getPrice():
        print (Fruit.price)
    def __getPrice(self):
        Fruit.price = Fruit.price + 10
        print (Fruit.price)
    count = staticmethod(__getPrice)
if __name__ == "__main__":
    apple = Fruit()
    apple.getColor()
    Fruit.count()
    banana = Fruit()
    Fruit.getPrice()
# 输出:red
# 10
# 10
@classmethod
def getPrice(cls):
    print (cls.price)
def __getPrice(cls):
    cls.price = cls.price + 10
    print (cls.price)
count = classmethod(__getPrice)

8.3.3 内部类的使用

class Car:
    class Door:
        def open(self):
            print ("open doot")
    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()
# 输出:open doot
# open doot
# car run

8.3.4 __init__方法

class Fruit:
    def __init__(self, color):
        self.__color = color
        print (self.__color)
    def getColor(self):
        print (self.__color)
    def setColor(self, color):
        self.__color = color
        print (self.__color)
if __name__ == "__main__":
    color = "red"
    fruit = Fruit(color)
    fruit.getColor()
    fruit.setColor("blue")
# 输出:red
# red
# blue

8.3.5 __del__方法

class Fruit:
    def __init__(self):
        self.__color = color
        print (self.__color)
    def  __del__(self):
        self.__color = ""
        print ("free ...")
    def grow(self):
        print ("grow ...")
if __name__ == "__main__":
    color = "red"
    fruit = Fruit(color)
    fruit.grow()

8.3.6 垃圾回收机制

import gc
class Fruit:
    def __init__(self, name, color):
        self.__name = name
        self.__color = color
    def getColor(self):
        return self.__color
    def setColor(self):
        self.__color = color
    def getName(self):
        return self.__name
class FruitShop:
    def __init__(self):
        self.fruits = []
    def addFruit(self, fruit):
        fruit.parent = self
        self.fruits.append(fruit)
if __name__ == "__main__":
    shop = FruitShop()
    shop.addFruit(Fruit("apple", "red"))
    shop.addFruit(Fruit("banana", "yellow"))
    print (gc.get_referrers(shop))
    del shop
    print (gc.collect())
# 输出:[{'_Fruit__name': 'apple', '_Fruit__color': 'red', 'parent':
# <__main__.FruitShop object at 0x0000020DAAB712B0>}, {'_Fruit__name':
# 'banana', '_Fruit__color': 'yellow', 'parent': <__main__.FruitShop
# object at 0x0000020DAAB712B0>}, {'__name__': '__main__', '__doc__':
# None, '__package__': None, '__loader__':
# <_frozen_importlib_external.SourceFileLoader object at 0x0000020DAA8EC048>,
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'
# (built-in)>, '__file__': 'D:/Python/零基础学 python/第8章 面向对象编程/内容.py',
# '__cached__': None, 'gc': <module 'gc' (built-in)>, 'Fruit':
# <class '__main__.Fruit'>, 'FruitShop': <class '__main__.FruitShop'>, 'shop':
# <__main__.FruitShop object at 0x0000020DAAB712B0>}]
# 1856

8.3.7 类的内置方法

#         1)__new__()
class Singleton(object):
    __instance = None
    def __init__(self):
        pass
    def __new__(cls, *args, **kwargs):
        if Singleton.__instance is None:
            Singleton.__instance = object.__new__(cls, *args, **kwd)
        return Singleton.__instance
            2)__getattr__(), __setattr__(), __getattribute__()
class Fruit(object):
    def __init__(self, color = "red", price = 0):
        self.__color = color
        self.__price = price
    def __getattribute__(self, item):
        return object.__getattribure__(self, name)
    def __setattr__(self, key, value):
        self.__dict__[name] = value
if __name__ == "__main__":
    fruit = Fruit("blue", 10)
    print (fruit.__dict__.get("_Fruit__color"))
    fruit.__dict__["_Fruit__price"] = 5
    print (fruit.__dict__.get("_FRUIT__price"))
           3)__getitem__()
class FruitShop:
    def __getitem__(self, i):
        return self.fruits[i]
if __name__ == "__main__":
    shop = FruitShop()
    shop.fruits = ["apple","banana"]
    print (shop[1])
    for itme in shop:
        print (itme,end=" ")
# 输出:banana
# apple banana 
           4)__str__()
class Fruit:
    '''Fruit类'''
    def __str__(self):
        return self.__doc__
if __name__ == "__main__":
    fruit = Fruit()
    print (str(fruit))
    print (fruit)
#输出:Fruit类
# Fruit类
          5)__call__()
class Fruit:
    class Growth:
        def __call__(self):
            print ("grow ...")
    grow = Growth()
if __name__ == "__main__":
    fruit = Fruit()
    fruit.grow()
    Fruit.grow()
# 输出:grow ...
# grow ...

8.3.8 方法的动态特性

## 动态添加方法
class Fruit:
    pass
def add(self):
    print ("grow ..")
if __name__ == "__main__":
    Fruit.grow = add
    fruit = Fruit()
    fruit.grow()
# 输出:grow ...
## 动态更新方法
class Fruit():
    def grow(self):
        print ("grow ...")

def update():
    print ("grow ...")
if __name__ == "__main__":
    fruit = Fruit()
    fruit.grow()
    fruit.grow = update
    fruit.grow()
# 输出:grow ...
# grow ...

8.4 继承

8.4.1 使用继承

class Fruit:
    def __init__(self, color):
        self.color = color
        print ("fruit's color: %s" % self.color)
    def grow(self):
        print ("grow ...")
class Apple(Fruit):
    def __init__(self, color):
        Fruit.__init__(self. color)
        print ("apple's color: %s" % self.color)
class Banana(Fruit):
    def __init__(self, color):
        Fruit.__init__(self.color)
        print ("banana's color: %s" % self.color)
    def gruit(self):
        print ("banana grow ...")
if __name__ == "__main__":
    apple = Apple("red")
    apple.grow()
    banana = Banana("yellow")
    banana.grow()
## 使用super()调用父类
class Friut(object):
    def __init__(self):
        print ("parent")
class Apple(Friut):
    def __init__(self):
        super(Apple, self).__init__()
        print ("child")
if __name__ == "__main__":
    Apple()
# 输出:parent
# child

8.4.2 抽象基类

from abc import ABCMeta, abstractmethod
class Fruit(metaclass=ABCMeta):
    @abstractmethod
    def grow(self):
        pass
class Apple(Fruit):
    def grow(self):
        print ("Apple growing")
if __name__ == "__main__":
    apple = Apple()
    apple.grow()
# 输出:Apple growing

8.4.3 多态性

class Fruit:
    def __init__(self, color=None):
        self.color = color
class Apple(Fruit):
    def __init__(self, color="erd"):
        Fruit.__init__(self, color)
class Banana(Fruit):
    def __init__(self, color="yellow"):
        Fruit.__init__(self, color)
class FruitShop:
    def sellFruit(self, fruit):
        if isinstance(fruit, Apple):
            print ("sell apple")
        if isinstance(fruit, Banana):
            print ("sell apple")
        if isinstance(fruit, Apple):
            print ("sell Friut")

8.4.3 多态性

class Fruit:
    def __init__(self, color=None):
        self.color = color
class Apple(Fruit):
    def __init__(self, color="erd"):
        Fruit.__init__(self, color)
class Banana(Fruit):
    def __init__(self, color="yellow"):
        Fruit.__init__(self, color)
class FruitShop:
    def sellFruit(self, fruit):
        if isinstance(fruit, Apple):
            print ("sell apple")
        if isinstance(fruit, Banana):
            print ("sell apple")
        if isinstance(fruit, Apple):
            print ("sell Friut")
if __name__ == "__main__":
    shop = FruitShop()
    apple = Apple("red")
    banana = Banana("yellow")
    shop.sellFruit(apple)
    shop.sellFruit(banana)
# 输出:sell apple
# sell Friut
# sell apple

8.4.4 多重继承

class Fruit:
    def __init__(self):
        print ("initialize Fruit")
    def grow(self):
        print ("grow ...")
class Vegetable(object):
    def __init__(self):
        print ("initialize Vegetable")
    def plant(self):
        print ("plant ...")
class Watermelon(Vegetable, Fruit):
    pass
if __name__ == "__main__":
    w = Watermelon()
    w.grow()
    w.plant()
# 输出:initialize Vegetable
# grow ...
# plant ...

  

8.4.5 Mixin机制

 1 class Fruit:
 2     def __init__(self):
 3         pass
 4 class HuskedFruit(Fruit):
 5     def __init__(self):
 6         print ("initialize HuskedFruit")
 7     def husk(self):
 8         print ("husk ...")
 9 class DecorticatedFruit(Fruit):
10     def __init__(self):
11         print ("initialize DecorticatedFruit")
12     def decorticat(self):
13         print ("decorticat ...")
14 class Apple(HuskedFruit):
15     pass
16 class Banana(DecorticatedFruit):
17     pass
View Code
 1 class Fruit:  # 水果
 2     def __init__(self):
 3         pass
 4 class HuskedFruit(object):  # 削皮水果
 5     def __init__(self):
 6         print ("initialize HuskedFruit")
 7     def husk(self):  # 削皮方法
 8         print ("husk ...")
 9 class DecorticatedFruit(object):  #削皮水果
10     def __init__(self):
11         print ("initialize DecorticatedFruit")
12     def decorticat(self):  # 削皮方法
13         print ("decorticat ...")
14 class Apple(HuskedFruit, Fruit):  # 是水果,并且是削皮水果。
15     pass
16 class Banana(DecorticatedFruit, Fruit):  # 是水果,并且是削皮水果。
17     pass
View Code

8.5 运算符的重载

 1 class Fruit:
 2     def __init__(self, price=0):
 3         self.price = price
 4     def __add__(self, other):
 5         return self.price + other.price
 6     def __gt__(self, other):
 7         if self.price > other.price:
 8             flag = True
 9         else:
10             flag = Fruit
11         return flag
12 class Apple(Fruit):
13     pass
14 class Banana(Fruit):
15     pass
16 if __name__ == "__main__":
17     apple = Apple(3)
18     print ("苹果的价格:",apple.price)
19     banana = Banana(2)
20     print ("香蕉的价格:",banana.price)
21     print (apple > banana)
22     total = apple + banana
23     print ("合计:",total)
24 # 输出:苹果的价格: 3
25 # 香蕉的价格: 2
26 # True
27 # 合计: 5
View Code
 1 import sys
 2 class Stream:
 3     def __init__(self, file):
 4         self.file = file
 5     def __lshift__(self, obj):
 6         self.file.write(str(obj))
 7         return self
 8 class Fruit(Stream):
 9     def __init__(self, price = 0, file = None):
10         Stream.__init__(self, file)
11         self.price = price
12 class Apple(Fruit):
13     pass
14 class Banana(Fruit):
15     pass
16 if __name__ == "__main__":
17     apple = Apple(2, sys.stdout)
18     banana = Banana(3, sys.stdout)
19     endl = "\n"
20     apple<<apple.price<<endl
21     banana<<banana.price<<endl
22 # 输出:2
23 # 3
View Code

8.6 Python与设计模式

8.6.1 设计模式简介

8.6.2 设计模式示例--Python实现工厂方法

 1 class Factory:
 2     def createFruit(self, fruit):
 3         if fruit == "apple":
 4             return Apple()
 5         elif fruit == "banana":
 6             return Banana
 7 class Fruit:
 8     def __str__(self):
 9         return "fruit"
10 class Apple(Fruit):
11     def __str__(self):
12         return "apple"
13 class Banana(Fruit):
14     def __str__(self):
15         return "banana"
16 if __name__ == "__main__":
17     factory = Factory()
18     print (factory.createFruit("apple"))
19     print (factory.createFruit("banana"))
20 # 输出:apple
21 # <class '__main__.Banana'>
View Code

8.8 习题

1) 则么查看一个类的所有属性。
2) 为什么创建类函数的时候需要添加self变量?可以使用其他变量如this代替self吗?
3) 则么理解Pthon中一切皆对象。
4) 汽车、轮船、火车等都属于交通工具。联系实际情况,编写类Traffic,并继承其他实现类Car,Ship和Train。

posted @ 2018-12-31 14:17  无声胜有声  阅读(242)  评论(0)    收藏  举报