Class类简单代码
#!/bin/env python#!coding=utf-8class SchoolMember(object):##定义一个父类def __init__(self,name,gender,nationality):self.name=nameself.gender=genderself.nation=nationali
·
#!/bin/env python
#!coding=utf-8
class SchoolMember(object): ##定义一个父类
def __init__(self,name,gender,nationality):
self.name=name
self.gender=gender
self.nation=nationality
##类中包含三个变量
def tell(self): ##一个方法
print "Hi,my name is %s,I am from %s" %(self.name,self.nation)
class Student(SchoolMember): ##定义子类student
def __init__(self,Name,Class,Gender,Score,Nation='CN'):
SchoolMember.__init__(self,Name,Gender,Nation) ##将父类的三个变量导入子类
self.Class=Class
self.Gender=Gender
def payTuition(self,amount):
if amount < 6999:
print "GET OFF"
else:
print "Welcome!"
class Teacher(SchoolMember): ##定义另一个子类teacher
def __init__(self,name,gender,salary,subject,nation='Fr'):
#SchoolMember.__init__(self,name,gender,nation)
self.salary=salary ##这里没有用student类的方式将父类的变量导入子类,而是一个一个手动赋予的
self.subject=subject
self.name=name
self.gender=gender
self.nation=nation
def show(self):
print "Hi,I am teaching %s,my salary is %s" %(self.name,self.salary)
s1=Student('zhang','Python','man','99') ##s1赋值4个
s1.tell() ##调用父类的方法tell
s1.payTuition(7000) ##调用自己本身的类方法
s2=Student('dang','Python','woman','100') ##s2
s2.tell() ##调用父类的子方法tell
s2.payTuition(8000)
s2.age=21 ##给s2新添一个变量age
print s2.age
t=Teacher('ALex','Woman','9000','Linux')
t.tell()
t.show()
另外还要介绍两个python中自带的函数setattr与getattr
setattr:
语法:
setattr(Class.SchoolMember,'age',18) ##给类SchoolMember(父类)添加变量age,默认值为18
setattr(Class.Student,'age',20) ##给类Student(子类)添加变量age,默认值为20
值得一提的是,当调用子类Student的age是,输出为20,因为子类会覆盖父类的值
getattr
当我们需要按照某个顺序执行类中的方法时需要用到getattr
v=['tell','tell1','tell2']
假设我们想执行tell方法,但又不能直接输入。此时即可用到getattr
t=Teacher('ALex','Woman','9000','Linux')
getattr(t,v[0])()
即可调用出tell方法!
更多推荐
已为社区贡献11条内容
所有评论(0)