python中类的继承

时间:2024-09-07 17:07:08

python中类的继承

在python中面向对象编程中实现继承,以下面一个实例进行说明。

class SchoolMenber():
# __init__类似于c++中的构造函数
# __init__必须赋予一个self的参数,也可以有其他参数用于初始化
def __init__(self, name, age):
self.name = name
self.age = age
print("Initialized SchoolMember:%s" % self.name) def tell(self):
print("Name: %s, Age: %s" % (self.name, self.age)) # __del__类似于c++中的析构函数
def __del__(self):
print("%s has been removed from database" % self.name) class Teacher(SchoolMenber):
# 把基本类的名称作为一个元组放在新类定义时的括号中,实现了继承
def __init__(self, name, age, salary):
# 注意!这里调用了基本类的__init__,初始化了基本类中的部分
# 重要!python不会自动调用基本类的构造函数,要coder亲自调用它
SchoolMenber.__init__(self, name, age)
self.salary = salary
print("Initialized Teacher: %s" % self.name) def tell(self):
print("Teacher: %s, Salary: %s" % (self.name, self.salary)) class Student(SchoolMenber):
def __init__(self, name, age, grade):
SchoolMenber.__init__(self, name, age)
self.grade = grade
print("Initialized Student: %s" % self.name) def tell(self):
print("Student: %s, Grade: %s" %(self.name, self.grade))