定义一个 class 的时候,可以从某个现有的 class 继承,新的 class 称为子类(Subclass),而被继承的 class 称为基类、父类或超类(Base class、Super class)
class DerivedClassName(BaseClassName1):
.
.
BaseClassName(示例中的基类名)必须与派生类定义在一个作用域内。除了类,还可以用表达式,基类定义在另一个模块中时这一点非常有用:
class DerivedClassName(modname.BaseClassName):
#!/usr/bin/python3
# 类定义
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))
zth = student('zth',10,40,5)
zth.speak()
执行结果:
zth 说:我 10 岁了,在读 5 年级
>>> class Animal(object):
... def run(self):
... print('animal is running ...')
... def __run(self):
... print(' I am a private method.')
...
>>>
>>> class Dog(Animal):
... def eat(self):
... print(' dog is eating ')
...
>>>
>>> dog = Dog()
>>>
>>> dog.run()
animal is running ...
>>> dog.eat()
dog is eating
>>> dog.__run()
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Dog' object has no attribute '__run'
>>>
多重继承的定义:
class DerivedClassName(Base1, Base2, Base3):
.
.
#!/usr/bin/python3
# -*-coding:UTF-8-*-
#类定义
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 ZTH(speaker,student):
a = ''
def __init__(self,n,a,w,g,t):
student.__init__(self, n, a, w, g)
speaker.__init__(self, n, t)
zth = ZTH('zth',10,40,5,'Python3')
zth.speak() #方法名同,默认调用的是在括号中排前地父类的方法
执行结果:
我叫 zth,我是一个演说家,我演讲的主题是 Python3