继承和方法重写

  • 单继承
class DerivedClassName(BaseClassName1):
    <statement -1>
    .
    .
    <statement -N>
圆括号中须要注意
a、基类的顺序,若基类中有相同的方法名,而杂志类使用时未指定,Python 从左至右搜索,即方法在子类中未找到时,从左到右查找基类中是否包含方法
b、BaseClassName(示例中的基类名)必须与 派生类定义在一个做用域,除了类,还能够用表达式,基类定义在另外一个模块中时这点很是有用
#定义People类
class People:
    #定义基本属性
    name = ''
    age = 0
    _weight = 0 #私有化的属性,类外部没法直接访问
    #定义构造方法
    def __init__(self,name,age,_weight):
        self.name = name
        self.age =  age
        self._weight = _weight
    def speak(self):
        print ("%s 说:我 %s 岁 "%(self.name,self.age))

p = People('runob',10,30)
p.speak()

#单继承
class Student(People):
    grade = ''
    def __init__(self,name,age,_weiht,grade):
        People.__init__(self,name,age,_weiht)   #引用父类的构造函数
        self.grade= grade
    def speak(self):                            #重写父类的方法
        print ("%s 说:我 %s 岁了,我在读 %s 年级"%(self.name,self.age,self.grade))

s = Student('ken',10,60,3)
s.speak()

#输出结果
runob 说:我 10 岁 
ken 说:我 10 岁了,我在读 3 年级
  • 多继承
class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    <statement-N>
圆括号须要注意
a、父类的顺序,若是父类中有相同的方法名,而在子类使用时未肯定,Python从左至右搜索,即方法在子类中未找到时,从左到右查找父类中是否包含方法
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# @Time    : 2017/8/17 0017 11:43
# @Author  : Aries
# @Site    :
# @File    : ss.py
# @Software: PyCharm Community Edition

# 类定义
class people:
    # 定义基本属性
    name = ''
    age = 0
    # 定义私有属性,私有属性在类外部没法直接进行访问
    __weight = 0

    # 定义构造方法
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s 说: 我 %d 岁。" % (self.name, self.age))


# 单继承示例
class student(people):
    grade = ''

    def __init__(self, n, a, w, g):
        # 调用父类的构函
        people.__init__(self, n, a, w)
        self.grade = g

    # 覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))


# 另外一个类,多重继承以前的准备
class speaker():
    topic = ''
    name = ''

    def __init__(self, n, t):
        self.name = n
        self.topic = t

    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))


# 多重继承
class sample(speaker, student):
    a = ''

    def __init__(self, n, a, w, g, t):
        student.__init__(self, n, a, w, g)
        speaker.__init__(self, n, t)


test = sample("Tim", 25, 80, 4, "Python")
test.speak()  # 方法名同,默认调用的是在括号中排前地父类的方法

#输出
我叫 Tim,我是一个演说家,我演讲的主题是 Python

  • 方法重写
重写是子类的方法覆盖父类的方法,要求方法名和参数都相同
class Parent:
    def myMethod(self):
        print ("调用父类的方法")

class Child(Parent):
    def myMethod(self):        #重写父类的方法
        print ("调用子类的方法")

c = Child()
c.myMethod()

#输出
调用子类方法

  • 检查继承
想要查看一个类是不是另外一个的子类,能够使用内建 issubclass() 函数
s = Student('ken',10,60,3)   #s是Studennt的实例
s.speak()
print issubclass(Student,People) #检查一个类是不是另外一个类的子类,Student继承了People
print Student.__bases__          #查看类的基类
print isinstance(s,Student)      #检查一个对象是不是一个类的实例
相关文章
相关标签/搜索