您的位置:首页 > 编程语言 > Python开发

python重载运算符

2015-09-03 20:45 921 查看
[code]class Time60(object):
    'Time60 - trace hours and minutes'
    def __init__(self,h,m):
        'constructor - takes hours and minutes'
        self.h=h
        self.m=m
    def __str__(self):
        'string representation'
        return "%02d:%02d" % (self.h,self.m)
    __repe__=__str__
    def __add__(self,other):
        'overloading the addition operator'
        m=self.m+other.m
        h=(self.h+other.h+m//60)
        return self.__class__(h,m%60)
    def __iadd__(self,other):
        'overloading in-place addition'
        m=self.m+other.m
        h=(self.h+other.h+m//60)
        self.m=m%60
        self.h=h;
        return self
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)
x=Time60(12,5)
print(x)
a=RandSeq([1,2,34,45,7,9,5,3,7])
it=iter(a)
for x in range(5):
    print(it.__next__())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: