python基础语法 010 类和对象6-2 重写父类

2.3 重写父类方法

2.3.1 重写

重写:就是子类中,有一个和父类相同名字的方法,在子类中的方法会覆盖父类中同名的方法

  • 当子类和父类具有同样的方法或者属性的时候
  • 父类还是用父类的,子类不再用父类的,而是用自己的
  • 子类也可以自定义自己的方法
1)子类和父类具有同样的初始化属性
python 复制代码
"""
子类可以实现自己独有的方法
子类可以覆盖父类的方法  ====>重写
"""

class Phone:
    def __init__(self, number):
        self.number =number


class smartPhone(Phone):
    '智能手机'
    def __init__(self, number, brand):
        self.number =number
        self.brand =brand


#当子类和父类具有同样的方法或者属性的时候
#父类还是用父类的,子类不再用父类的,而是用自己的

normal = Phone('1')
# smart = smartPhone('1')
"""报错,只能使用子类自己的
TypeError: __init__() missing 1 required positional argument: 'brand'"""

smart = smartPhone('1', 'xiaoyi')
print(smart) #<__main__.smartPhone object at 0x000001CA89A268B0>
2)子类和父类具有同样的方法

Iphone类虽然继承smartPhone类但自定义了call方法,smartPhone类继承了Phone类的call方法,

smartPhone类实例无法调用Iphone类实例自定义的call方法,还是使用Phone类的call方法

例子:

python 复制代码
class Phone:
    def __init__(self, number):
        self.number =number

    def  call(self, to, records = False):
        "打电话"
        print("{}给{}打电话".format(self.number, to))
        if records:
            self.record()

    def record(self):
        '录音'
        print("{}正在录音".format(self.number))

class smartPhone(Phone):
    '智能手机'
    def __init__(self, number, brand):
        self.number =number
        self.brand =brand

    def watch_movie(self, name):
        print("{}正在看电影".format(name))
    pass

class Iphone(smartPhone):
    # brand = '苹果'

    #重写
    def __init__(self, number):
        self.number = number
        self.brand = '苹果'

    def face_time(self):
        """录屏"""
        print("正在直播{}".format(self.number))

    def call(self, to, records = False, face = False):

        print("{}给{}打电话".format(self.number, to))
        if records:
            self.record()

        if face:
            self.face_time()


#重写例子2:
iphone = Iphone('苹果15')
iphone.call('开始',face=True)
"""结果
苹果15给开始打电话
正在直播苹果15"""

smart =smartPhone('123', 'xiaoyi')
# smart.call('xiaoer', face = True)
#TypeError: call() got an unexpected keyword argument 'face'
3)子类也可以自定义自己的方法

上面例子中smartPhone类类自定义了自己的方法watch_movie,该方法不存在父类中

2.3.2 调用重名父类的方法

子类如果需要父类的初始化方法,则子类的初始化方法里面,需要调用父类的初始化方法

否则解释器自己就不会执行父类的初始化方法

子类重写了父类的方法之后,如何在子类中再调用父类的方法?

  • 方法1:父类名.方法名(self)
  • 方法2:super().方法名()

方法1:父类名.方法名(self)

例子:

python 复制代码
class BenzCar:
    brand = '奔驰'
    country = '德国'

    @staticmethod
    def pressHorn():
        print("嘟嘟~~")
    def __init__(self, color, engineSN):
        self.color = color
        self.engineSN = engineSN

    def changeColor(self, newColor):
        self.color = newColor

class Benz2016(BenzCar):
    price = 502222
    model = 'Benz2016'
 
    #先调用父类的初始化方法
    def __init__(self, color,engineSN, weight):
        BenzCar.__init__(self,color,engineSN)
        self.weight = weight
        self.oilweight = 0

方法二:super()

super() 超继承:使用父类当中的方法,不管是静态方法、实例方法、类方法都可以用

问题:子类GirlYiFu要复用父类YiFu的sell方法,自己又对sell方法有自己独特的使用,如果直接用父类引用,父类存在的参数,子类不存在,怎么处理?

ANS:使用super函数

super()使用的时候,方法参数不需要加上self参数

super()使用在方法上
python 复制代码
class YiFu:
    def __init__(self):
        pass

    def sell(self, price = True):
        print('商场正在卖衣服')

        if price:
            print('衣服价格打八折')

class GirlYiFu(YiFu):
    def __init__(self):
        pass

    def sell(self, price = True, unprice = False):

        #弊端:如果父类有很多参数要传,这样父类添加参数,调用也要更改
        #YiFu().sell(price)   or YiFu.sell(price)
        """===更改  super()
        super()  == YiFu('', '')
        """

        super().sell(price)

        print('女装独特卖衣服的技巧')

# normal = YiFu()
# normal.sell()
"""结果
商场正在卖衣服
衣服价格打八折"""

nvzhuang = GirlYiFu()
nvzhuang.sell()

"""结果:
商场正在卖衣服
衣服价格打八折
女装独特卖衣服的技巧
"""
super函数使用在__init__

问题:继承的方法用到父类的__init__的实例属性,自己又定义了init方法

ANS:

python 复制代码
class YiFu:
    def __init__(self, num, brand):
        self.num = num
        self.brand =brand
        

   
class GirlYiFu(YiFu):
    def __init__(self, num):
        super().__init__(num,'apple')
相关推荐
thinkMoreAndDoMore38 分钟前
深度学习(3)-TensorFlow入门(常数张量和变量)
开发语言·人工智能·python
kngines1 小时前
【Python量化金融实战】-第1章:Python量化金融概述:1.4 开发环境搭建:Jupyter Notebook、VS Code、PyCharm
python·量化金融
kngines1 小时前
【Python量化金融实战】-第1章:Python量化金融概述:1.2 Python在量化金融中的优势与生态
python·量化金融
wapicn991 小时前
‌挖数据平台对接DeepSeek推出一键云端部署功能:API接口驱动金融、汽车等行业智能化升级
java·人工智能·python·金融·汽车·php
蓝桉8021 小时前
图片爬取案例
开发语言·数据库·python
逸狼1 小时前
【JavaEE进阶】Spring DI
java·开发语言
wang_yb1 小时前
『Python底层原理』--Python整数为什么可以无限大
python·databook
敲上瘾2 小时前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
阑梦清川2 小时前
Jupyter里面的manim编程学习
python·jupyter·manim
my_styles2 小时前
2025-alibaba-Sentinel组件
java·开发语言·sentinel