pythonのいくつかの特性
2430 ワード
class Student(object):
say="this is a student class"
def __init__(self,name,age):#
self.name = name
self.age = age
@classmethod#
def showClassMethod(cls):
print "call classmethod"
print cls.say
@staticmethod# ,
def showStaticMethod():
print "call static method"
print Student.say
@property#
def sex(self):
print "call property"
return self._sex
@sex.setter# sex
def sex(self,value):
print "call setter"
self._sex = value
def getSex(self):# sex
return self._sex
def showAll(self):#
print "call instance method"
print self.age,self.name,self.sex,self.getSex()
def __del__(self):#
print "call destructor"
def __str__(self):#
return "student object:(name:%s)(age:%d)" % (self.name,self.age)
def __repr__(self):# :s
return self.__str__()
def __getattr__(self, item):#
if item == "score":
return lambda :99
elif item == "dog":
return "xiaohuang"
else:
raise "attr error"
def __call__(self, *args, **kwargs): #
print "__call__ self:"
for i in range(len(args)):#
print args[i]
for i in kwargs:#
print i,kwargs[i]
print "call:my name is zhengjinwei"
Student.showClassMethod() #
s = Student("zhengjinwei",24)
s.sex = "male" # sex , Student object
s.grade = "1" #
print s.grade
print s # __str__
print s.score() # __getattr__
print s.dog # __getattr__
if callable(s):
s(1,2,3,name="zjw",age=24) # __call__
s.showClassMethod()
s.showStaticMethod()
s.showAll()
結果:
<span style="font-size:18px;">call classmethod
this is a student class
call setter
1
student object:(name:zhengjinwei)(age:24)
99
xiaohuang
__call__ self:
1
2
3
age 24
name zjw
call:my name is zhengjinwei
call classmethod
this is a student class
call static method
this is a student class
call instance method
24 zhengjinwei call property
male male
call destructor
</span>