# -*- coding:utf-8 -*-
#类定义
class people(object):
#定义基本属性
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 is speaking:I am %d years old, %d weight."%(self.name,self.age,self.__weight))
# 实例化
p = people("Tom",17,100)
p.speak()
print '*'*40
#单继承示例
class student(people):
grade = ''
def __init__(self,n1,a1,w1,g1):
people.__init__(self,n1,a1,w1)
self.grade = g1
def speak(self):
print("%s is speaking: I am %d years old,and I am in grade %d"%(self.name,self.age,self.grade))
s = student('ken',20,60,3)
s.speak()
#另一个类,多重继承之前的准备
class speaker(): #需改为 class Speaker(object):
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
# def speak(self):
# print("I am %s,I am a speaker!My topic is %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,9,"Python")
test.speak()```#方法名同,默认调用的是在括号中排前地父类的方法```
若想要让`test.speak()`调用的是student父类中的speak( )方法,则想要指定。方法有两种:
方法一:
最简单的方法是把对象调用转换成类调用,需要注意的是这时self参数需要显式传递,将sample的类改写为:
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)
def speak(self):
student.speak(self) #self是必须的
test = sample("Tim",25,80,9,"Python")
test.speak()
#此时该speak的方法是调用student类里的speak方法,而不是speaker类里的方法。
缺点:
比如说如果修改了父类名称,那么在子类中会涉及多处修改,另外,Python是允许多继承的语言,如上所示的方法在多继承时就需要重复写多次,显得累赘。为了解决这些问题,Python引入了super()机制
方法二:
使用super()机制,代码如下:
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)
def speak(self):
super(sample,self).speak() # super()机制
test = sample("Tim",25,80,9,"Python")
test.speak()
在使用super()的过程中出现过
“TypeError: must be type, not classobj”错误
关于TypeError,在定义两个父类的时候加入他们的父类(object),如下,再尝试一次,因为Python 2中的classobj不算做一种type,如果你用Python 3的话应该就没有这种问题了。