"Talk is cheap,so I'll give you code",但还是得废话一句,Python真是一种美妙的语言,但凡事有利有弊,毕竟有一句话“动态编译一时爽,代码重构火葬场”。
仔细看注释,讲解都在注释中
先定义两个类
class Person(object): #继承自object类
count = 0;#静态变量
@classmethod
def printCount(cls):
print cls.count
def __init__(self, name, birth):#相当于构造方法
self._name = name#单下划线开头表示保护属性 类似java里的protected
self._birth = birth
def printMessage(self):
print 'name:',self._name,'birthday:', self._birth
class Person2(object): #继承自object类
def __init__(self, name):#相当于构造方法
self._name = name#单下划线开头表示保护属性 类似java里的protected
def printMessage(self):
print 'name:',self._name
def printId(self):
print 'I am person2'
'''
p1 = Person('程旭远', '199X-XX-XX')
p1.printMessage()
p2 = Person2('Lincon');
p2.printId()
'''
再定义一个继承自Person的类
class Student(Person):
def __init__(self, name, birth, score):
#super(Student, self).__init__(name, birth) 也可这么写
Person.__init__(self, name, birth)
self.__score = score;
def printMessage(self):#方法重写
print 'name:',self._name,'birthday:', self._birth, 'score:', self.__score
s1 = Student('程旭远', '199X-XX-XX' , '99.6')
s1.printMessage()
#静态变量与方法也参与继承
print s1.count
Student.count += 1
Student.printCount()
运行结果:name: 程旭远 birthday: 199X-XX-XX score: 99.6
0
1
多继承
class Teacher(Person, Person2):
def __init__(self, name,birth, age):
Person.__init__(self, name, birth)
Person2.__init__(self, name)
self.__age = age
def printTeacherMessage(self):
print 'age:', self.__age
teacher = Teacher('liu', '19XX-XX-XX', 44)
teacher.printMessage()#在第一个父类里找到 就不往下找
teacher.printId()#只存在于第二个父类
teacher.printTeacherMessage()#自身存在该方法
运行结果:name: liu birthday: 19XX-XX-XX
I am person2
age: 44