• 继承part1


    '''面向对象编程三大特性:继承,多态,封装'''
    '''什么是类的继承:类的继承跟现实生活中的父、子、孙子、重孙子继承关系一样,父类又称为基类;python中类的继承分为:单继承和多继承''' class Dad: money = 100 def __init__(self, name): print('实例化过程...') self.name = name def hit_son(self): print('%s正在打儿子' % self.name) class Son(Dad): pass print(Son.money) # Son.hit_son() # 报错,缺少一个参数self print(Dad.__dict__) # {'__module__': '__main__', 'money': 100, '__init__': <function Dad.__init__ at 0x000001E4EFBE8040>, 'hit_son': <function Dad.hit_son at 0x000001E4EFBE8670>, '__dict__': <attribute '__dict__' of 'Dad' objects>, '__weakref__': <attribute '__weakref__' of 'Dad' objects>, '__doc__': None} print(Son.__dict__) # {'__module__': '__main__', '__doc__': None} s1 = Son('alex') # 类Son实例化时需要传入一个参数name,相当于执行的是父类的__init__(自己本身没有__init__,所以就到父类中去找) print(s1.__dict__) # {'name': 'alex'} print(s1.name) print(s1.money) s1.hit_son() # 子类继承了父类所有的属性,如果子类定义的属性和父类重名了,并不是覆盖,而是先在自己属性字典里找,有的话就不在父类属性字典找 class Dad_1: money = 100 def __init__(self, name): print('实例化过程...') self.name = name def hit_son(self): print('%s正在打儿子' % self.name) class Son_1(Dad): money = 10000 def __init__(self, name, age): self.name = name self.age = age def hit_son(self): print('来自子类的方法...') print(Son_1.__dict__) # {'__module__': '__main__', 'money': 10000, '__doc__': None} print(Son_1.money) # 10000 s2 = Son_1('wupeiqi', 20) # 此时子类本身有__init__,所以初始化时按照子类的初始化方法进行传参 print(s2.__dict__) # {'name': 'wupeiqi', 'age': 20} print(s2.money) s2.hit_son()
    while True: print('studying...')
  • 相关阅读:
    python学习笔记(29)-操作excel
    python学习笔记(28)-unittest单元测试-执行用例
    python学习笔记(27)-unittest单元测试-测试用例
    python学习笔记(26)-request模块
    python学习笔记(25)-继承
    c++ 流基本概念
    友元函数、类和运算符重载
    c++中的引用
    c++重点知识点
    指针和结构体
  • 原文地址:https://www.cnblogs.com/xuewei95/p/14672111.html
Copyright © 2020-2023  润新知