当前位置:   article > 正文

面向对象——继承

面向对象——继承

102.继承

在这里插入图片描述
在这里插入图片描述

#测试继承语法结构

class Person:
    def __init__(self,name,age):
        self.name = name
        self.__age = age  #私有属性

    def say_age(self):
        pass
        #print('年龄是{0}'.format(self.age))

class Student(Person):
    def __init__(self,name,age,score):
        Person.__init__(self,name,age)
        self.score = score

print(Student.mro())  #Student.mro()显示子类的继承结构
s = Student("马宝林",18,80)
s.say_age()
#print(s.age)  #父类里面是私有的,私有方法属性,子类继承了但是不能用
print(s._Person__age)
print(dir(s))
print(s.name)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
D:\python\python37\python.exe F:/python/mypro01/mypro07.py
[<class '__main__.Student'>, <class '__main__.Person'>, <class 'object'>]
18
['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'say_age', 'score']
马宝林
  • 1
  • 2
  • 3
  • 4
  • 5

103.方法的重写

在这里插入图片描述

#测试继承方法的重写

class Person:
    def __init__(self,name,age):
        self.name = name
        self.__age = age  #私有属性

    def say_age(self):
        print('我的年龄是{0}'.format(self.__age))

    def say_introduction(self):
        print("我的名字是:{}".format(self.name))

class Student(Person):
    def __init__(self,name,age,score):
        Person.__init__(self,name,age)
        self.score = score

    def say_introduction(self):
        
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/913414
推荐阅读
相关标签
  

闽ICP备14008679号