【python】Python面向对象之——多态

Python中多态

什么是多态

多态指的是一类事物有多种形态。

定义:多态是一种使用对象的方式,子类重写父类方法,调用不同子类对象的相同父类方法,可以产生不同的执行结果。

① 多态依赖继承

② 子类方法必须要重写父类方法

首先定义一个父类,其可能拥有多个子类对象。当我们调用一个公共方法时,传递的对象不同,则返回的结果不同。

好处:调用灵活,有了多态,更容易编写出通用的代码,做出通用的编程,以适应需求的不断变化!

例如,我们可以定义一个Animal类,其中有一个make_sound方法用于输出动物的声音。然后,我们可以创建多个子类,如Dog、Cat和Bird,它们分别覆盖make_sound方法,输出不同的声音。

class Animal:
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("汪汪汪!")

class Cat(Animal):
    def make_sound(self):
        print("喵喵喵!")

class Bird(Animal):
    def make_sound(self):
        print("叽叽喳喳!")
 
dog = Dog()
dog.make_sound()  # 输出:汪汪汪!

cat = Cat()
cat.make_sound()  # 输出:喵喵喵!

bird = Bird()
bird.make_sound()  # 输出:叽叽喳喳!

当一个子类同时重写了__new____init__方法时,创建对象的过程如下:

  1. 首先,Python会调用子类的__new__方法来创建一个实例。如果子类没有定义__new__方法,则会调用父类的__new__方法。这个过程会一直继续到object基类为止。

  2. __new__方法应该返回一个新创建的实例。在__new__中,你可以进行一些额外的处理,如改变返回的实例类型或根据某些条件改变实例的行为。

  3. 接着,在__new__返回的实例上,Python会调用__init__方法。如果子类定义了自己的__init__方法,那么它会被调用;如果没有,就会调用父类的__init__方法,以此类推,直到到达object类。

  4. __init__不同,Python不会自动调用父类的__init__方法。你必须在子类的__init__方法中显式地调用它,通常使用super()函数。

例如:

class Base:
    def __new__(cls, *args, **kwargs):
        print("Base's __new__ called")
        return super().__new__(cls)
    
    def __init__(self):
        print("Base's __init__ called")

class Derived(Base):
    def __new__(cls, *args, **kwargs):
        print("Derived's __new__ called")
        return super().__new__(cls)
    
    def __init__(self):
        print("Derived's __init__ called")
        super().__init__()

# 创建Derived的实例
instance = Derived()

在这个例子中:

  • 创建Derived实例时,Derived__new__方法首先被调用,然后是Base__new__方法(通过super())。
  • 之后,Derived__init__方法被调用,它又显式地调用了Base__init__方法(同样通过super())。

因此,正确的调用顺序是:

  1. Derived__new__
  2. Base__new__
  3. Derived__init__
  4. Base__init__

注意,__new__是一个静态方法,而__init__是一个实例方法。这意味着__new__可以访问类对象,但不能访问实例(除非它已经被创建),而__init__则是在实例已经创建后被调用的。

练习

1.老板安排员工工作,销售员、程序员、保安三人分别执行不同的工作

class Employee:
    def work(self):
        pass
    
class Seller(Employee):
    def work(self):
        print("销售")

class Programmer(Employee):
    def work(self):
        print("程序员")


class Bouncer(Employee):
    def work(self):
        print("保安")
            
            
class Boss():
    def manage(self, employee: Employee):
        employee.work()

s = Seller()
p = Programmer()
bou = Bouncer()
boss = Boss()
boss.manage(s)
boss.manage(p)
boss.manage(bou)
销售
程序员
保安

2.现有一个休息室,有"提供人员休息场地"的功能,销售休息时睡觉,程序员休息时打游戏,保安休息时抽烟

class Employee:
    def rest(self):
        pass
    
class Seller(Employee):
    def rest(self):
        print("睡觉")

class Programmer(Employee):
    def rest(self):
        print("玩游戏")
        
class Bouncer(Employee):
    def rest(self):
        print("抽烟")
        
class Restroom(object):
    def provide_rest(self, employee: object):
        employee.rest()
        
Restroom().provide_rest(Seller())
Restroom().provide_rest(Programmer())
Restroom().provide_rest(Bouncer()) 


睡觉
玩游戏
抽烟

3.使用键盘打字,使用不同的键盘发出的声音是不一样的

class Keyboard():
    def sound(self):
        pass
    
class Membrane(Keyboard):
    def sound(self):
        print("Soft sound")
        
class Mechanical(Keyboard):
    def sound(self):
        print("Hard sound")
        
class Person():
    def use(self, keyboard: Keyboard):
        keyboard.sound()

Person().use(Membrane())
Person().use(Mechanical())
Soft sound
Hard sound

4.使用电脑机,电脑由键盘、鼠标、显示器、主机构成,请使用面向对象思想描述台式机的属性和功能

class Computer:
    def __init__(self,keyboard,mouse,display,host) -> None:
        self.keyboard = keyboard
        self.mouse = mouse
        self.display = display
        self.host = host
        
    def work(self,program):
        print(f"{self.host}正在使用{program}")
        
c1 = Computer("樱桃","罗技G302","宏碁QM27","华硕")
c1.work("pycharm")
华硕正在使用pycharm

5.使用open函数,在代码同级目录创建file1.txt文件,内容为hello file1

f = open("file1.txt", "w")
f.write("hello file1")
f.close()

6.使用open函数,在代码所在目录的父级目录创建file2.txt,内容为hello file2

f2 = open("../file2.txt", "w")
f2.write("hello file2")
f2.close()

7.读取file1.txt的内容,并且输出在控制台

with open("file1.txt", "r") as f:
    print(f.read())
hello file1
  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值