二十二. Python基础(22)--继承

● 知识框架

 

● 继承关系中self的指向

当一个对象调用一个方法时,这个方法的self形参会指向这个对象

class A:

    def get(self):

        self.say()

 

    def say(self):

        print('AAAAA')

 

class B(A):

    def say(self):

        print('BBBBB')

 

b = B()

b.get() # BBBBB

# 当一个对象调用一个方法时,这个方法中的self就指向这个对象

# 子类先调用自己的属性或方法, 子类自己没有才调父类的

# 如果是class B(A):pass, 那么结果是'AAAAA'

print(dir(b))

# ['__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__', 'cls_att', 'get', 'name', 'say']

print(b.__dict__)

# {'name': 'Arroz'}

print(vars(b))

# {'name': 'Arroz'}

print(b.__class__)

# <class '__main__.B'>

print(B.__class__)

#<class 'type'> # 实例关系

print(B.__bases__)

# (<class '__main__.A'>,) # 继承关系

print(B.__doc__)

# This is class B

 

● 经典类(old-style)和新式(new-style)类调用父类方法的区别

class Dog(Animal):

    def __init__(self, name):

        # Animal.__init__(self, name) # 经典类, 注意不要遗漏self

        super().__init__(name) # 新式类, 等价于super(Dog, self).__init__(name),读作"调用Dog的父类

         的方法(calling Dog's parent's method)"

内置函数super([type[, object-or-type]])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

 

● 综合案例

class Base:

    cls_attr = 'class attribute'

    def __init__(self, name, age, job):

        self.name = name

        self.age = age

        self.job = job

    def bmeth(self):

        print('Base method')

 

class Derived_0(Base):

    def dmeth(self):

        print('Derived method')

 

print(type(Base)) # <class 'type'>, 元类

print(type(Derived_0)) # <class 'type'>, 元类

 

# 没有添加新的对象属性, 不用使用super()

d_0 = Derived_0('Paul', 55, 'Singer')

print(d_0.job)

 

# 下面添加了添加了新的对象属性, 需要使用super()

class Derived_1(Base):

    def __init__(self, name, age, job, hobby):

        super(Derived_1, self).__init__(name, age,job) #
子类调用父类方法时, 参数的个数不能缺少.

        self.hobby = hobby

    def dmeth(self):

        print('Derived method')

    def show(self):

        print(self.name, self.age, self.job,self.hobby)

 

class Derived_2(Base):

    def __init__(self, name, hobby):

        super(Derived_2, self).__init__(name, 20, 'teacher') # 子类调用父类方法时, 参数的个数不能缺少, 并且可以把已知的属性先传给父类的构造函数

        self.hobby = hobby

    def dmeth(self):

        print('Derived method')

    def show(self):

        print(self.name, self.age, self.job,self.hobby)

 

class Derived_3(Base):

    def __init__(self, hobby):

        super(Derived_3, self).__init__("Paul", 22, 'painter') # 子类调用父类方法时, 参数的个数不能缺少, 并且可以把已知的属性先传给父类的构造函数

        self.hobby = hobby

 

    def dmeth(self):

        print('Derived method')

 

    def show(self):

        print(self.name, self.age, self.job, self.hobby)

 

#① #######################################################

b = Base('Arroz', 18, 'teacher')

print(Base.__dict__) # 类的属性

'''

{'__module__': '__main__', 'cls_attr': 'class attribute', '__init__': <function Base.__init__ at 0x00000000028EA840>, 'bmeth': <function Base.bmeth at 0x00000000028EA8C8>,

'__dict__': <attribute '__dict__' of 'Base' objects>, '__weakref__': <attribute '__weakref__' of 'Base' objects>, '__doc__': None}

'''

print(b.__dict__) # 对象属性

'''

{'name': 'Arroz', 'age': 18, 'job': 'teacher'}

'''

print('----------------------')

#② #######################################################

d_1 = Derived_1('Arroz', 18, 'teacher','swimming')

d_1.show() # Arroz 18 teacher swimming

print('----------------------')

#③ #######################################################

d_2 = Derived_2('Pwter', 'skating')

d_2.show() # Pwter 20 teacher skating

print('----------------------')

#④ #######################################################

d_3 = Derived_3('jogging')

d_3.show() # Paul 22 painter jogging

 

二十二. Python基础(22)--继承的更多相关文章

  1. 二十四. Python基础(24)--封装

    二十四. Python基础(24)--封装 ● 知识结构   ● 类属性和__slots__属性 class Student(object):     grade = 3 # 也可以写在__slots ...

  2. 二十六. Python基础(26)--类的内置特殊属性和方法

    二十六. Python基础(26)--类的内置特殊属性和方法 ● 知识框架 ● 类的内置方法/魔法方法案例1: 单例设计模式 # 类的魔法方法 # 案例1: 单例设计模式 class Teacher: ...

  3. 二十五. Python基础(25)--模块和包

    二十五. Python基础(25)--模块和包 ● 知识框架   ● 模块的属性__name__ # my_module.py   def fun1():     print("Hello& ...

  4. JAVA基础知识总结:一到二十二全部总结

    >一: 一.软件开发的常识 1.什么是软件? 一系列按照特定顺序组织起来的计算机数据或者指令 常见的软件: 系统软件:Windows\Mac OS \Linux 应用软件:QQ,一系列的播放器( ...

  5. python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法

    python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法window安装redis,下载Redis的压缩包https://git ...

  6. Bootstrap <基础二十二>超大屏幕(Jumbotron)

    Bootstrap 支持的另一个特性,超大屏幕(Jumbotron).顾名思义该组件可以增加标题的大小,并为登陆页面内容添加更多的外边距(margin).使用超大屏幕(Jumbotron)的步骤如下: ...

  7. python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码

    python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码 python的json.dumps方法默认会输出成这种格式"\u535a\u ...

  8. python3.4学习笔记(二十五) Python 调用mysql redis实例代码

    python3.4学习笔记(二十五) Python 调用mysql redis实例代码 #coding: utf-8 __author__ = 'zdz8207' #python2.7 import ...

  9. python3.4学习笔记(二十二) python 在字符串里面插入指定分割符,将list中的字符转为数字

    python3.4学习笔记(二十二) python 在字符串里面插入指定分割符,将list中的字符转为数字在字符串里面插入指定分割符的方法,先把字符串变成list然后用join方法变成字符串str=' ...

随机推荐

  1. java开发中中文编码问题

    //ajax以get方式提交,字符串中包含中文 //后台struts中对该string的set方法中 this.jsonString = new String(jsoString.getBytes(& ...

  2. L2-026. 小字辈

    本题给定一个庞大家族的家谱,要请你给出最小一辈的名单. 输入格式: 输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号.随后第二行 ...

  3. 节约内存:Instagram的Redis实践(转)

    Instagram可以说是网拍App的始祖级应用,也是当前最火热的拍照App之一,Instagram的照片数量已经达到3亿,而在Instagram里,我们需要知道每一张照片的作者是谁,下面就是Inst ...

  4. mysql密码的查看/修改

    2.Mysql的Root密码忘记----查看或修改方法 2.1)启动命令行:windows微标键+R 2.2)在命令行输入taskkill /f /im mysqld.exe 回车,暂停Mysql服务 ...

  5. STATS 326 Applied Time Series

    STATS 326Applied Time SeriesASSIGNMENT THREEDue: 2 May 2019, 11.00 am(Worth 6% of your final grade)H ...

  6. 一道简单树形dp

    题意:给定一棵树,从中选出一些节点,使得不成父子关系的节点对数最多.问这个最大值是多少. 思路:首先既然是给定一颗树,先要选择合适的数据结构,来保存这颗树.由于这颗树只关心根节点在哪里,所以只需要用一 ...

  7. Codeforces Round #467 (Div. 2) B. Vile Grasshoppers

    2018-03-03 http://codeforces.com/problemset/problem/937/B B. Vile Grasshoppers time limit per test 1 ...

  8. devm_kzalloc【转】

    本文转载自:https://blog.csdn.net/liuhuahan/article/details/42145507 看内核代码的时候看到这个函数不理解它的具体作用然后就上网上查,但是网上只查 ...

  9. 【问题解决:信息提示】SpringBoot启动时提示The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path

    问题描述 springboot程序在启动时提示信息 [2018-10-24 21:59:05.214] - 440 信息 [restartedMain] --- org.apache.catalina ...

  10. 微信小程序unionid获取问题

    微信小程序使用login获取unionid时可能获取不到,原因可能是该微信账号没有关注小程序所在公众号等.但在微信小程序中使用微信注册,必须要用unionid注册时,大部分用户就会因此无法注册成功. ...