Python之面向对象类的继承与多态(04)

发布时间:2021-12-03 公开文章

I am not a designer nor a coder. I'm just a guy with a point-of-view and a computer.

筑基<融合<元婴<分神<渡劫<大乘
 

 

 

类的继承

#类的继承

class Father: #基类
    def walking(self):
        print('多走路有益健康!')

class Son(Father): #派生类
    pass

#创建子类实例
Joe = Son()
Joe.walking()
多走路有益健康!
#在子类中调用父类的方法
class Father: #基类
    def walking(self):
        print('多走路有益健康!')

class Son(Father): #派生类
    def walking(self):
        Father.walking(self)#调用父类的方法
        print('饭后要多多散步')

#创建父类实例
Steven = Father()
print('Father class')
Steven.walking()
print('Son class')
#创建子类实例
Joe = Son()
Joe.walking()
Father class
多走路有益健康!
Son class
多走路有益健康!
饭后要多多散步
# 定义类
class Motor: #基类 或 父类

    '''__init__: 初始化对象
       price, capacity 有默认值,表示是选项参数
    '''

    def __init__(self, name, price = 15,
                 capacity = 1500): 
        self.name = name 
        self.price = price 
        self.capacity = capacity       

    def equip(self, award):#配备奖励
        self.price = self.price + award

    def __repr__(self): #设置输出格式
        msg = '{0:8s}, 售价{1:7.2f} 万,排气量 {2:,} c.c.'
        return msg.format(
            self.name, self.price, self.capacity)

class Hybrid(Motor): #派生类 或 子类   

    def equip(self, award, cell = 2.18):
        Motor.equip(self, award + cell)

    def tinted(self, opr):
        if opr == 1:
            return '极致蓝'
        elif opr == 2:
            return '魅力红'        


#创建父类对象
stand = Motor('standard') 
apollo = Motor('Apollo', price = 15.2,
               capacity = 1795)    
print(apollo, '不含电子锁')    
apollo.equip(1.2) #加价

# 创建子类对象
inno = Hybrid('Innovate', 32.8, 2495)
inno.equip(1.1)
print('Hybrid is', inno.tinted(2))

print('-- 三种车款 --')
for item in (stand, apollo, inno):        
   print(item)
Apollo  , 售价  15.20 ,排气量 1,795 c.c. 不含电子锁
Hybrid is 魅力红
-- 三种车款 --
standard, 售价  15.00 ,排气量 1,500 c.c.
Apollo  , 售价  16.40 ,排气量 1,795 c.c.
Innovate, 售价  36.08 ,排气量 2,495 c.c.
#类的继承

class Father: #基类一
    def walking(self):
        print('多走路有益健康!')

class Mother: #基类二
    def riding(self):
        print('I can ride a bike!')

class Son(Father, Mother): #派生类
    pass

#创建子类实例
Joe = Son()
Joe.walking()
Joe.riding()
多走路有益健康!
I can ride a bike!
#继承的搜索顺序

class Parent(): #有两个方法
    def show1(self):
        print("Parent method one")

    def show2(self):
        display("Parent method two")

class Son(Parent):
    def display(self):
        print('Son method')

class Daughter(Parent):
    def show2(self):
        print('Daughter method one')

    def display(self):
        goodNews('Daughter method two')

class Grandchild(Son, Daughter):
    def message(self):
        print('Grandchild method')

eric = Grandchild()
#先找到自己的方法
eric.message()
#按顺序, Grandchild > Son
eric.display()
#Grandchild > Son > Daughter
eric.show2()
#Grandchild > Son > Daughter > Parent
eric.show1()
Grandchild method
Son method
Daughter method one
Parent method one

继承机制

#子类覆盖父类的方法
class Mother(): #父类
    def display(self, pay):
        self.price = pay
        if self.price >= 30000:
            return pay * 0.9

class Son(Mother): #子类
    def display(self, pay): #覆盖display方法
        self.price = pay
        if self.price >= 30000:
            print('8折:', end = ' ')
            return pay * 0.8

Joe = Son() #创建对象
print(Joe.display(35000))
8折: 28000.0
#内部函数super()

class Mother(): #父类
    def display(self, pay):
        self.price = pay

        if self.price >= 30000:            
            self.price *= 0.9
        else:
            self.price
        print(' = {:,}'.format(self.price))        

class Son(Mother): #子类
    def display(self, pay): #覆盖display方法        
        self.price = pay
        super().display(pay)

        if self.price >= 30000:            
            self.price *= 0.8
        else:
            self.price        
        print('8折 {:,}'.format(self.price))

Liz = Mother() #基类对象
print('40000 * 9折', end = '')
Liz.display(40000)

Joe = Son() #创建子类对象
print('35000 * 9折', end = '')
Joe.display(35000)
40000 * 9 = 36,000.0
35000 * 9 = 31,500.0
8 25,200.0
#__init__()方法调用super()

class Parent(): #父类
    def __init__(self):
        print('I am parent')

class Child(Parent): #子类
    def __init__(self, name):
        super().__init__()
        print(name, 'is child')

tom = Child('Tomas') #子类实例
I am parent
Tomas is child
# __bases__属性动态记录父类

class Father():#父类一
    def display(self, name):
        self.name = name
        print('Father name is', self.name)

class Mother():#父类二
    def display(self, name):
        self.name = name
        print('Mother name is', self.name)

#子类继承Father, Mother
class Child(Father, Mother):
    pass

class Son(Father): #子类继承Father
    pass

print(Child.__name__, '类, 继承两个基类')
for item in Child.__bases__:
    print(item)

Tom = Son()#子类实例,只有一个父类
Tom.display('Eric')
print(Son.__name__,'类,一个父类')
print(Son.__bases__)
Son.__bases__ = (Mother,)
Tom.display('Judy')
Child , 继承两个基类
<class '__main__.Father'>
<class '__main__.Mother'>
Father name is Eric
Son 类,一个父类
(<class '__main__.Father'>,)
Mother name is Judy
#使用property

class Student:
    def __init__(self, birth):
        self.birth = birth

tom = Student('1998/5/21')
print('Tom 生日', tom.birth)
Tom 生日 1998/5/21
#使用property -- 2

class Student:
    def __init__(self, birth):
        if birth == None:
            raise ValueError('不能是空字串')
        #__birth: 私有屬性
        self.__birth = birth
    def getBirth(self):
        return self.__birth
    def setBirth(self, birth):
        self.__birth = birth

tom = Student('1998/5/21')
print('Tom 生日', tom.getBirth())
tom.setBirth('1999/5/21')
print('Tom 生日', tom.getBirth())
Tom 生日 1998/5/21
Tom 生日 1999/5/21
#使用property()函数 -- 3

class Student:
    def __init__(self, birth):
        if birth == None:
            raise ValueError('不能是空字串')
        #__birth: 私有屬性
        self.__birth = birth
    def getBirth(self):
        return self.__birth
    def setBirth(self, birth):
        self.__birth = birth
    def delBirth(self):
        del self.__birth
    birth = property(getBirth, setBirth,
                     delBirth, 'birth 特性说明')

tom = Student('1998/5/21') # 创建对象
print('Tom 生日', tom.birth)
tom.birth = '1998/5/21'
Tom 生日 1998/5/21
#使用property()函数 -- 4

class Student:
    def __init__(self, birth):
        if birth == None:
            raise ValueError('不能是空字符串')
        #__birth: 私有属性
        self.__birth = birth

    @property #getter为birth创建一个特性
    def birth(self):
        return self.__birth

    @birth.setter #附加 setter 设置器
    def birth(self, birth):
        self.__birth = birth

    @birth.deleter # 附加 deleter删除器
    def birth(self):
        del self.__birth    

tom = Student('1998/5/21') # 创建对象
print('Tom 生日', tom.birth)
tom.birth = '1998/5/21'
Tom 生日 1998/5/21
# 在父类使用特性
class Student:
    def __init__(self, birth):
        if birth == None:
            raise ValueError('不能是空字符串')
        #__birth: 私有属性
        self.__birth = birth

    @property #getter为birth创建一个特性
    def birth(self):
        return self.__birth

    @birth.setter #附加 setter 设置器
    def birth(self, value):
        if not isinstance(value, str):
            raise TypeError('应该是字符串')
        self.__birth = value

    @birth.deleter # 附加 deleter删除器
    def birth(self):
        raise AttributeError('属性不能删除')
#继承的子类使用特性
class Person(Student):    

    @property #getter为birth创建一个特性
    def birth(self):
        return super().birth

    @birth.setter #附加 setter 设置器
    def birth(self, value):
        super(Person, Person).birth.__set__(
            self, value)

    @birth.deleter # 附加 deleter删除器
    def birth(self):
        super(Person, Person).birth.__delte__(self)    

eric = Person('1998/5/21') # 创建对象
print('Eric 生日', eric.birth)
Eric 生日 1998/5/21

抽象类与多态

#定义抽象类 - 导入abc模块
from abc import ABCMeta, abstractmethod

class Person(metaclass = ABCMeta): #抽象类    
    @abstractmethod #装饰器 - 抽象方法
    def display(self, name):
        pass
    def pay(self):
        self.display(self.name, self.salary)

#实现Person类
class Clerk(Person):

    def __init__(self):
        self.name = 'Steven'
        self.salary = 28000

    def display(self, name, salary):        
        print(name, 'is a Clerk')
        print('薪水:', salary)

#创建对象,调用抽象类的一般方法pay()
steven = Clerk()
steven.pay()
Steven is a Clerk
薪水: 28000
#定义多态
class Motor(): #父类
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def equip(self):
        return self.price

    def show(self):
        return self.name

class sportCar(Motor):#子类
    def equip(self):        
        return self.price * 1.15 

class Hybrid(Motor): #子类
    def equip(self):
        return self.price *1.2
altiz = Motor('Altiz', 487500) #父类对象
print('{:8s} 定价 {:,}'.format(altiz.show(), altiz.equip()))

inno = sportCar('Innovate', 638000) #子类对象
print('{:8s} 定价 {:,}'.format(inno.show(), inno.equip()))

suv = Hybrid('SUV', 1150000) #子类对象
print('{:8s} 定价 {:,}'.format(suv.show(), suv.equip()))
Altiz    定价 487,500
Innovate 定价 733,700.0
SUV      定价 1,380,000.0
class Vehicle(): #与三个类无关联
    def equip(self):
        return 2500 
    def show(self):
        return 'Qi无线充电座'

def unite(article): #定义方法来输出各对象
    print('{:12s}, 售价 {:,} '.format(
        article.show(), article.equip()))

altiz = Motor('Altiz', 487500)
unite(altiz)
inno = sportCar('Innovate', 638000)
unite(inno)
suv = Hybrid('SUV', 1150000) #子类对象
unite(suv)

car = Vehicle()#Vehicle 对象
unite(car)
Altiz       , 售价 487,500 
Innovate    , 售价 733,700.0 
SUV         , 售价 1,380,000.0 
Qi无线充电座     , 售价 2,500
from datetime import date

#组合的简易作法
class Student: #学生
    def __init__(self, *name):
        self.name = name

class Room: #教室
    def __init__(self, title, tday):
        self.title = title
        self.today = tday
        print('上课日期:', self.today)
        print('上课教室:', self.title)

class School: #学校
    def __init__(self, student, room):
        self.student = student
        self.room = room

    def display(self):
        print('Student:', self.student.name)

tday = date.today() #获取今天日期
eric = Student('Eric', 'Vicky', 'Emily') #Student对象
abc123 = Room('Abc123', tday) #上课教室
tc = School(eric, abc123) #School实例
tc.display() #调用方法
上课日期: 2019-08-29
上课教室: Abc123
Student: ('Eric', 'Vicky', 'Emily')