python 调用父类方法

 时间:2026-02-15 17:39:31

1、打开jupyter notebook,新建一个PYTHON文档。

python 调用父类方法

2、class Product:

    def sold(self):

        print("Product can be sold")

        

class Phone(Product):

    pass

首先我们要知道继承父类的方法,子类的定义名字后面加上父类的名字。

python 调用父类方法

3、iphone = Phone()

iphone.sold()

我们来测试一下是否已经继承了,已经继承了,直接可以这样调用父类的方法。

python 调用父类方法

4、class Product:

    def sold(self):

        print("Product can be sold")

        

class Phone(Product):

    def sold(self):

        print("Phones can be sold")

        

iphone = Phone()

iphone.sold()

如果我们重写了方法,那么调用的时候会显示重写的方法。

python 调用父类方法

5、class Product:

    def sold(self):

        print("Product can be sold")

        

class Phone(Product):

    def sold(self):

        super().sold()

        print("Phones can be sold")

        

iphone = Phone()

iphone.sold()

如果想重写并且把父类的方法继承,那么就可以用super()。

python 调用父类方法

6、class Product:

    def __init__(self):

        self.name = "NAME"

        

class Phone(Product):

    def __init__(self):

        super().__init__()

        

iphone = Phone()

print(iphone.name)

但是我们可以用super()来进行调用。

python 调用父类方法

7、class Product:

    def __init__(self):

        self.name = "NAME"

        

class Phone(Product):

    def __init__(self):

        Product.__init__(self)

        

iphone = Phone()

print(iphone.name)

除了用super(),还可以用名字直接调用。

python 调用父类方法

8、class Product:

    def __init__(self):

        self.name = "NAME"

        

class Phone:

    def __init__(self):

        Product.__init__(self)

        

iphone = Phone()

print(iphone.name)

如果用名字直接调用,那么在定义子类的时候就不用在后面跟着父类的名字了。

python 调用父类方法

  • 3dmax实际操作程序界面组成结构
  • PS软件怎样画出一只可爱的浣熊?
  • 怎么使用3D绘图软件Cinema 4D创建一块立体草坪
  • 3DSMAX如何打造真实的海景
  • 3Dmax牙膏盖材质设置教程
  • 热门搜索
    有助于睡眠的方法 ppt目录怎么做 虾干怎么做好吃 大闸蟹怎么做好吃 表白方法 挽留爱情的方法 苹果图片大全 怎么制作铃声 十种最好吃的素包子馅 一年级古诗大全