python继承,判断类型,多态
2016-12-04 08:24
489 查看
1、python中继承
如果已经定义了Person类,需要定义新的Student和Teacher类时,可以直接从Person类继承:
class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender
定义Student类时,只需要把额外的属性加上,例如score:
class Student(Person): def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score = score
一定要用 super(Student, self).__init__(name, gender) 去初始化父类,否则,继承自 Person 的 Student 将没有 name 和 gender。
函数super(Student, self)将返回当前类继承的父类,即 Person ,然后调用__init__()方法,注意self参数已在super()中传入,在__init__()中将隐式传递,不需要写出(也不能写)。
实例:
# -*- coding: utf-8 -*- class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') def run_twice(animal): animal.run() animal.run() a = Animal() d = Dog() c = Cat() print('a is Animal?', isinstance(a, Animal)) print('a is Dog?', isinstance(a, Dog)) print('a is Cat?', isinstance(a, Cat)) print('d is Animal?', isinstance(d, Animal)) print('d is Dog?', isinstance(d, Dog)) print('d is Cat?', isinstance(d, Cat)) run_twice(c)View Code
相关文章推荐
- Python 继承、多重继承、多态、isinstance判断类型、type()获取变量类型、dir()获取变量的所有属性
- Python中继承、多态、多继承、判断类型、json.load()解析、获取/设置对象信息
- Python面向对象,类,继承,多态及鸭子类型,获取类的类型,方法和属性(类似java的反射)
- python中如何判断一个变量的数据类型?(原创)
- python 判断字符串中字符类型的常用方法
- python中如何判断一个变量的数据类型?(原创)
- python技巧31[判断操作系统类型]
- Python中的类型关系和继承关系
- python判断操作系统类型
- 写几个带继承关系的类,使用直接强转的方式,以及使用as转换, 并且练习is的类型判断
- 判断异常类型,全面捕获Python的异常
- python 判断数据类型
- Python类型判断
- Python动态类型,怎么判断是输入数据的合法性?
- Python天天美味(4) - isinstance判断对象类型(转)
- python 类型true,false判断
- Python isinstance判断对象类型
- Python天天美味(4) - isinstance判断对象类型
- .net 继承&多态情况下,调用方法的判断规则
- python技巧31[判断操作系统类型]