定制类
打印类信息
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
def __str__(self):
return '(Student: %s, %s, %s)' % (self.name, self.gender, self.score)
__repr__ = __str__
s = Student('Bob', 'male', 88)
print s
定义了 __str__ 和 __repr__方法,定制自己的类对象的打印信息
定义类的比较函数
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if self.score > s.score:
return -1
elif self.score < s.score:
return 1
else:
if self.name > s.name:
return 1
else:
return -1
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
定义len函数
class Fib(object):
def __init__(self, num):
self.num = num
mylist = [0,1]
for i in range(1,num-1):
mylist.append(mylist[-1] + mylist[-2])
self.mylist = mylist
def __str__(self):
return '%s' %(self.mylist)
def __len__(self):
return len(self.mylist)
f = Fib(10)
print f
print len(f)
@property
class Student(object):
def __init__(self, name, score):
self.name = name
self.__score = score
@property
def score(self):
return self.__score
@score.setter
def score(self, score):
if score < 0 or score > 100:
raise ValueError('invalid score')
self.__score = score
@property
def grade(self):
if self.score >= 80:
return 'A'
elif self.score < 60:
return 'C'
else:
return 'B'
s = Student('Bob', 59)
print s.grade
s.score = 60
print s.grade
s.score = 99
print s.grade
限制类的属性
class Person(object):
__slots__ = ('name', 'gender')
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
__slots__ = ('name','gender','score')
def __init__(self,name,gender,score):
super(Student,self).__init__(name,gender)
self.score = score
s = Student('Bob', 'male', 59)
s.name = 'Tim'
s.score = 99
print s.score
__call__函数
class Fib(object):
def __call__(self,num):
mylist = [0,1]
for i in range(1,num-1):
mylist.append(mylist[-1] + mylist[-2])
return mylist
f = Fib()
print f(10)
一个类实例也可以成为一个可调用对象,需要实现__call__方法。