python 类继承 例子_pythonl类继承例子

本文介绍了一个简单的面向对象编程示例,通过定义Person、SchoolMember、Student及Teacher等类,演示了如何使用Python进行面向对象的设计。这些类展示了继承、封装等特性,并提供了具体的实例展示。
摘要由CSDN通过智能技术生成

#coding=utf-8

class Person(object):

def __init__(self,name,age):

self.name=name

self.age=age

def get_age(self):

return self.age

def get_name(self):

return self.name

def set_age(self,age):

if age>=0 and age<=150:

self.age=age

def set_name(self,name):

self.name=name

class SchoolMember(Person):

def __init__(self,name,age,school_name):

Person.__init__(self,name,age)

self.school_name=school_name

def get_school_name(self):

return self.school_name

def set_school_name(self,school_name):

self.school_name=school_name

class Student(SchoolMember):

def __init__(self,name,age,school_name,grade):

SchoolMember.__init__(self,name,age,school_name)

self.grade=grade

def get_grade(self):

return self.grade

def set_grade(self,grade):

self.grade=grade

class Teacher(SchoolMember):

def __init__(self,name,age,school_name,level):

SchoolMember.__init__(self,name,age,school_name)

self.level=level

def get_level(self):

return self.level

def set_level(self,level):

self.level=level

if __name__==‘__main__‘:

p=Person(‘xiaxiaoxu‘,18)

print p.get_age()

print p.get_name()

p.set_name(‘sam xia‘)

p.set_age(20)

print p.get_age()

print p.get_name()

s=SchoolMember(‘xiaxiaoxu‘,18,‘dalian maritime university‘)

print s.get_school_name()

s.set_school_name(‘peking university‘)

print s.get_school_name()

t=Student(‘xiaxiaoxu‘,20,‘peking university‘,‘grade one‘)

print t.get_grade()

t.set_grade(‘grade two‘)

print t.get_grade()

th=Teacher(‘xiaxiaoxu‘,20,‘dalian maritime university‘,‘professor‘)

print th.get_level()

th.set_level(‘teacher‘)

print th.get_level()

c:\Python27\Scripts>python task_test.py

18

xiaxiaoxu

20

sam xia

dalian maritime university

peking university

grade one

grade two

professor

teacher

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值