クラスのカスタマイズ

1767 ワード

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 rmf

rmf2 = RoundFloatManual(42.2)
print rmf2

rmf3 = RoundFloatManual(42.22)
print rmf3

rmf4 = 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, tue
print (mon + tue)

#print (mon-tue)

print id(mon)
mon += tue
print mon
print id(mon)