关于python中类的小总结2
一、特殊方法定制类,看一个程序吧:
class RoundFloatManual(object):
??? def __init__(self, val):
??? ??? assert isinstance(val, float),"Value must be a float!"
??? ??? self.value = round(val, 2)
??? def __str__(self):
??? ??? return '%.2f' % self.value
??? __repr__ = __str__
>>> r = RoundFloatManual(5.568)
>>> r
5.57
加法:
>>> class Time60(object):
??? def __init__(self, hr, min):
??? ??? self.hr = hr
??? ??? self.min = min
??? def __repr__(self):
??? ??? return '%d:%d' % (self.hr, self.min)
??? def __add__(self, other):
??? ??? return self.__class__(self.hr + other.hr, self.min + other.min)
???
>>> a = Time60(10, 30)
>>> b = Time60(5, 20)
>>> a + b
15:50
原位加:
class Time60(object):
??? def __init__(self, hr, min):
??? ??? self.hr = hr
??? ??? self.min = min
??? def __repr__(self):
??? ??? return '%d:%d' % (self.hr, self.min)
??? def __add__(self, other):
??? ??? return self.__class__(self.hr + other.hr, self.min + other.min)
??? def __iadd__(self, other):
??? ??? self.hr += other.hr
??? ??? self.min += other.min
??? ??? return self
>>> a = Time60(10, 30)
>>> b = Time60(5, 20)
>>> a += b
>>> a
15:50
与上面一样,当使用到“+”加好的时候,就去自动调用__add__方法,使用到“+=”的时候就去调用__iadd__()方法。
迭代器
>>> from random import choice
>>> class RandSeq(object):
??? def __init__(self, seq):
??? ??? self.data = seq
??? def __iter__(self):
??? ??? return self
??? def next(self):
??? ??? return choice(self.data)
>>> for eachItem in RandSeq(('rock', 'paper', 'scissors')):
??? ??? ??? print eachItem
??? ??? ???
scissors
rock
paper
paper
rock
paper
……
二、关于单双下划线开头的方法名
Python 用下划线作为变量前缀和后缀指定特殊变量。
_xxx????? 不能用'from module import *'导入
__xxx__ 系统定义名字
__xxx??? 类中的私有变量名
核心风格:避免用下划线作为变量名的开始。
参考http://saber7.iteye.com/blog/835141
?
未完……
关于python中类的小总结1关于python中类的小总结2