zoukankan      html  css  js  c++  java
  • super的用法1


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

    • python
      tags:
    • python

    # -*- coding: utf-8 -*-
    
    __metaclass__ = type
    
    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:UsersadminDesktoppythonfiless.py", line 24, in <module>
        li.about('lihua')
      File "C:UsersadminDesktoppythonfiless.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 方法。

  • 相关阅读:
    一起ORA-00028案例的处理过程
    Preferences偏好设置
    Snap Settings对齐设置
    Graphics Emulation图形模拟
    Network Emulation(网格模拟)
    Selection
    Edit编辑
    Build Settings 构建设置
    Player Settings-PC
    Build Settings发布设置
  • 原文地址:https://www.cnblogs.com/id88/p/14210888.html
Copyright © 2011-2022 走看看