首页 > 技术文章 > super的用法1

id88 2020-12-30 12:46 原文


title: super的用法1
data: 2018-4-5
categories:

  • python
    tags:
  • python

# -*- coding: utf-8 -*-

class Person:
    def __init__(self):
        self.height = 180

    def about(self, name):
        print('{} is about {}'.format(name, self.height))

# 继承Person类
class Girl(Person):
    def __init__(self):
        # super(Girl, self).__init__()
        self.age = 20

    def about(self, name):
	# super(Girl, self).about(name)
        print('{} is a girl, she is about {}, and she is {}'.format(name, self.height, self.age))

if __name__ == '__main__':
    li = Girl()
    li.about('lihua')

报错信息如下:

Traceback (most recent call last):
  File "C:\Users\admin\Desktop\pythonfile\ss.py", line 24, in <module>
    li.about('lihua')
  File "C:\Users\admin\Desktop\pythonfile\ss.py", line 20, in about
    print('{} is a girl, she is about {}, and she is {}'.format(name, self.height, self.age))
AttributeError: 'Girl' object has no attribute 'height'

报错信息提示 self.height 是不存在的,也就是说 Girl 类并没有从 Person 中继承过来这个属性。

因为 about()__init__()这两个方法都被重写了,而 Girl 中的额 __init__中根本就没有关于 self.height 的任何信息。

在子类中, __init__方法被重写了,为了调用父类的同方法,使用super(Girl, self).__init__()的方式。super 函数的参数,第一个是当前子类的类名字,第二个是 self,然后是点号,点号后面是所要调用的父类的方法。

同样子类重写的 about 方法中,也可以调用父类的 about 方法。

推荐阅读