python-面向对象-类与运算符-年龄相加(自存)

class Programer(object):
    def __init__(self,name,age):
        self.name=name
        if isinstance(age,int):
            self.age=age
        else:
            raise Exception('age must be int')
    def __eq__(self,other):
        if isinstance(other,Programer):
            if self.age==other.age:
                return True
            else:
                return False
        else:
            raise Exception('The type of object must be Programer')
    def __add__(self,other):
        if isinstance(other,Programer):
            return self.age+other.age
        else:
            raise Exception('The type of object must be Programer')
if __name__=='__main__':
    p1=Programer('Albert',35)
    p2=Programer('Bill',30)
    print(p1==p2)
    print(p1+p2)

发布了64 篇原创文章 · 获赞 4 · 访问量 4342

猜你喜欢

转载自blog.csdn.net/yuppie__1029/article/details/89402888
今日推荐