首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

种的定制

2012-09-15 
类的定制1. 定制自己的float类:class RoundFloatManual(object):def __init__(self, val):assert isinstan

类的定制
1. 定制自己的float类:

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 str(self.value)        return '%.2f' % self.value    __repr__ = __str__    #rmf = RoundFloatManual(42)#print rmfrmf2 = RoundFloatManual(42.2)print rmf2rmf3 = RoundFloatManual(42.22)print rmf3rmf4 = RoundFloatManual(42.222)print rmf4


2. 定制一个时间的类
class Time60(object):    'Time60 - track hours and minutes'    def __init__(self, hr, min):        'Time60 constructor -takes hours and minutes'        self.hr = hr        self.min = min    def __add__(self, other):        'Time60 - overloading the addition operator'        return self.__class__(self.hr + other.hr,                              self.min + other.min)    def __iadd__(self, other):        'Time60 - overloading in-place addition'        self.hr += other.hr        self.min = other.min        return self    def __str__(self):        'Time60 - string representation'        return '%d:%d' % (self.hr, self.min)    __repr__ = __str__mon = Time60(10, 30)tue = Time60(11, 15)print mon, tueprint (mon + tue)#print (mon-tue)print id(mon)mon += tueprint monprint id(mon)

热点排行