Python---继承与多态

本文详细探讨了Python编程中的继承概念,包括单一继承、多重继承以及如何利用继承实现代码复用。同时,介绍了多态性的原理和应用场景,展示了Python如何通过方法重写和接口一致来实现多态。通过实例解析,帮助读者深化对Python面向对象编程的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python从入门到高手(内部资源-配学习资料)_哔哩哔哩_bilibili

# 私有化
# 封装:1.私有化属性  2.定义公有set和get方法
# __属性:就是将属性私有化,访问范围仅仅限于类中
'''
1.隐藏属性不被外界随意修改
2.可以修改:通过函数
    def setXXX(self,XXX):
    3.筛选赋值内容
        if XXX是符合条件
            赋值
        else:
            不赋值
3.如果想获取某一个属性
    使用get函数
    def getXXX(self):
        return self.__XXX
'''

class Student:
    __age = 18  # 类属性

    def __init__(self, name, age):
        self.__name = name  # 长度必须6位
        self.__age = age
        self.__score = 25

    # 定义公有set(赋值)和get(取值)方法
    def setAge(self, age):
        if age > 0 and age < 120:
            self.__age = age
        else:
            print('年龄不在规定的范围内')

    def getAge(self):
        return self.__age

    # 修改名字的时候,长度必须6位
    def setName(self, name):
        if len(name) == 6:
            self.__name = name
        else:
            print('长度不是6位')

    def getName(self):
        return self.__name

    def __str__(self):
        return '姓名:{},年龄:{},考试分数:{}'.format(self.__name, self.__age, self.__score)


yupeng = Student('yupeng', 18)
print(yupeng)

yupeng.age = 21
yupeng.__score = 95  # 赋值不成功
print(yupeng)
yupeng.setAge(50)
print(yupeng.getAge())

-----------------------------------------------------------------------------------
class Student:
    __age = 18  # 类属性

    def __init__(self, name, age):
        self.__name = name  # 长度必须6位
        self.__age = age
        self.__score = 25

    # 定义公有set(赋值)和get(取值)方法
    def setAge(self, age):
        if age > 0 and age < 120:
            self.__age = age
        else:
            print('年龄不在规定的范围内')

    def getAge(self):
        return self.__age

    # 修改名字的时候,长度必须6位
    def setName(self, name):
        if len(name) == 6:
            self.__name = name
        else:
            print('长度不是6位')

    def getName(self):
        return self.__name

    def __str__(self):
        return '姓名:{},年龄:{},考试分数:{}'.format(self.__name, self.__age, self.__score)

    # attribute: setName  getName  __str__  __init__


yupeng = Student('yupeng', 18)
print(yupeng)

print(dir(Student))
print(dir(yupeng))
print(yupeng._Student__age)  # 伪私有,其实就是__age,只不过系统自动改名字了

------------------------------------------------------------------------------------------------------------------

#  在开发中看到一些私有化处理:装饰器
class Student:
    __age = 18  # 类属性

    def __init__(self, name, age):
        self.name = name  # 长度必须6位
        self.__age = age

    # 定义公有set(赋值)和get(取值)方法
    # 老版
    # def setAge(self, age):
    #     if age > 0 and age < 120:
    #         self.__age = age
    #     else:
    #         print('年龄不在规定的范围内')
    #
    # def getAge(self):
    #     return self.__age

    # 先有getXXX,再有set,get依赖于set
    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, age):
        if age > 0 and age < 120:
            self.__age = age
        else:
            print('年龄不在规定的范围内')

    def __str__(self):
        return '姓名:{},年龄:{},考试分数:{}'.format(self.__name, self.__age, self.__score)


s = Student('peng', 20)

s.name = 'xiaopeng'
s.age = 30
print(s.name)
print(s.age)

# 私有化赋值
# s.setAge(30)
# print(s.getAge())

-----------------------------------------------------------------------------------------------------------------

# 继承:is a, has a
'''
公路(Road):
    属性:公路名称,公路长度
车(Car):
    属性:车名,时速
    方法:1.求车名在那条公路上以多少的时速行驶多长,
        get_time(self,rood)
        2.初始化车属性信息__init__方法
        3.打印对象显示车的属性信息
'''
import random


class Road:
    def __init__(self, name, len):
        self.name = name
        self.len = len


class Car:
    def __init__(self, brand, speed):
        self.brand = brand
        self.speed = speed

    def get_time(self, road):  # road与r指向同一个空间地址
        ran_time = random.randint(1, 10)
        msg = '{}品牌的车在{}上以{}速度行驶{}小时'.format(self.brand, road.name, self.speed, ran_time)
        print(msg)

    def __str__(self):
        return '{}品牌的,速度:{}'.format(self.brand, self.speed)


#  创建实例化对象
r = Road('京藏高速', 12000)  # road与r指向同一个地址空间
audi = Car('奥迪', 120)
r.name = '京哈高速'
print(audi)
audi.get_time(r)  # 对象

------------------------------------------------------------------------------------------------------------

'''
知识点:
1.has a
一个类中使用了另外一种自定义的类型

student使用computer book

2.类型
系统类型
str int float
list dict tuple set
自定义类型:
算是自定义的类,都可以将其当成一种类型
s=Student
s是Student类型的对象
'''


class Computer:
    def __init__(self, brand, type, color):
        self.brand = brand
        self.type = type
        self.color = color

    def online(self):
        print('正在使用电脑上网...')

    def __str__(self):
        return self.brand + '---' + self.type + '---' + self.color


class Book:
    def __init__(self, bname, author, number):
        self.bname = bname
        self.author = author
        self.number = number

    def __str__(self):
        return self.bname + '---' + self.author + '---' + str(self.number)


class Student:
    def __init__(self, name, computer, book):
        self.name = name
        self.computer = computer
        self.books = []
        self.books.append(book)

    def borrow_book(self, book):
        for book1 in self.books:
            if book1.bname == book.bname:
                print('已经借过了')
                break
        else:
            # 将参数book添加到列表中
            self.books.append(book)
            print('添加成功!')

    def show_book(self):
        for book in self.books:  # book就是一个book对象
            print(book.bname)

    def __str__(self):
        return self.name + '---' + str(self.computer) + '---' + str(self.books)


computer = Computer('Dell', 'R14', 'black')
book = Book('盗墓笔记', '南派三叔', 10)
stu = Student('songsong', computer, book)
print(stu)
# 看借了哪些书
stu.show_book()
book1 = Book('鬼吹灯', '天下霸唱', 8)
stu.borrow_book(book1)
stu.show_book()

------------------------------------------------------------------------------------------------

# is a   base  父类 基类
# Exception
'''
继承:
Student,Employee,Doctor ------》都属于人类
相同代码---》代码冗余,可读性不高

将相同代码提取---》Person类
Student,Employee,Doctor---》继承Person

class Student(Person):
    pass
'''


class Person:
    def __init__(self, name, age):
        self.name = '匿名'
        self.age = 18

    def eat(self):
        print(self.name + '正在吃饭。。。')

    def run(self):
        print(self.name + '正在跑步。。。')


class Student(Person):
    def __init__(self, name, age):
        # 调用父类的__init__
        super().__init__(name, age)  # super() 父类对象
        print('------>student的init')


class Employee(Person):
    pass


class Doctor(Person):
    pass


s = Student('renwen', 18)
s.run()

# e = Employee()
# d = Doctor()

-----------------------------------------------------------------------------------------------

'''
特点:
1.如果类中不定义__init__,调用父类super class的__init__
2.如果类继承父类也需要定义自己的__init__,就需要在当前类的__init__调用一下父类__init__
3.如何调用父类__init__:
    super().__init__:
    super().__init__(参数)
    super(类名,对象).__inint(参数)
4.如果父类有eat(),子类也定义一个eat方法,默认搜索的原则:先找当前类,再去找父类
    s.eat()
    override:重写(覆盖)
    父类提供的方法不能满足子类的需求,就需要在子类中定义一个同名的方法,这种行为:重写
5.子类的方法也可以调用父类方法:
    super().方法名(参数)
'''


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(self.name + '正在吃饭。。。')

    def run(self):
        print(self.name + '正在跑步。。。')


class Student(Person):
    def __init__(self, name, age, clazz):
        # 调用父类的__init__
        super().__init__(name, age)  # super() 父类对象
        self.clazz = clazz
        print('------>student的init')

    def study(self, course):
        print('{}正在学习{}课程'.format(self.name, course))

    def eat(self, food):
        super.eat()
        print(self.name + '在吃狮子头盖饭' + food)


class Employee(Person):
    def __init__(self, name, age, salary, manager):
        super().__init__(name, age)
        self.salary = salary
        self.manager = manager


class Doctor(Person):
    def __init__(self, name, age, patients):
        super(Doctor, self).__init__(name, age)
        self.patients = patients


s = Student('jack', 18, 'python1905')
s.study('python')
s.eat('鱼香肉丝')

e = Employee(name='tom', age=25, salary=10000, manager='king')

lists = ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
d = Doctor('lucy', 30, lists)

----------------------------------------------------------------------------------------------

# class Person:
#     def __init__(self, name):
#         self.name = name
#
#     def eat(self):
#         print('------>eat1')
#
#     def eat(self, food):
#         print('------>eat', food)
#
#
# p = Person('jack')
# p.eat('狮子头')

class Base:
    def test(self):
        print('------Base------')


class A(Base):
    def test(self):
        print('------>AAAAAA')


class B(Base):
    def test1(self):
        print('------>BBBBBB')


class C(Base):
    def test2(self):
        print('------>CCCCCC')


class D(A, B, C):
    pass


d = D()
d.test()

import inspect

print(inspect.getmro(D))

'''
python允许多继承,
def 子类(父类1,父类2,...):
    pass
如果父类中有相同名称的方法
'''

-----------------------------------------------------------------

#  多继承的搜索顺序:经典类 新式类


class P1:
    def foo(self):
        print('p1--->foo')

    def bar(self):
        print('p1--->bar')


class P2:
    def foo(self):
        print('p2--->foo')


class C1(P1, P2):
    pass


class C2(P1, P2):
    def bar(self):
        print('C2--->bar')


class D(C1, C2):
    pass


d = D()
d.foo()

# 广度优先

------------------------------------------------------------------------------------------

# 多态 封装 继承----》面向对象
class Person:
    def __init__(self, name):
        self.name = name

    def feed_pet(self, pet):  # pet既可以接收cat,也可以接收dog,还可以接收tiger
        #  isinstance(obj,类)  ------》 判断obj是不是类的对象或者判断obj是不是该类子类的对象
        if isinstance(pet, Pet):
            print('{}喜欢养宠物:{},昵称是:{}'.format(self.name, pet.role, pet.nickname))
        else:
            print('不是宠物类型的。。。')


class Pet:
    role = 'Pet'

    def __init__(self, nickname, age):
        self.nickname = nickname
        self.age = age

    def show(self):
        print('昵称:{},年龄:{}'.format(self.nickname, self.age))


class Cat(Pet):
    role = '猫'

    def catch_mouse(self):
        print('抓老鼠。。。')


class Dog(Pet):
    role = '狗'

    def watch_house(self):
        print('看家高手。。。')


class Tiger:
    def eat(self):
        print("太可怕了,可以吃人。。。")


# 创建对象
cat = Cat('花花', 2)
dog = Dog('大黄', 4)
tiger = Tiger()
person = Person('家伟')
person.feed_pet(cat)
person = Person('pengpeng')
person.feed_pet(tiger)

'''
pet 父类             cat   dog子类
pet 大类型           cat   dog小类型
'''

-----------------------------------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值