您的位置:首页 > 编程语言 > Python开发

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: