運算符重載

運算符重載

1.運算符重載

python中使用每一個運算符都是在調(diào)用運算符對應(yīng)的方法(每個運算符都有自己對應(yīng)的方法)
某種類型的數(shù)據(jù)支不支持某個運算符,就看這個數(shù)據(jù)對應(yīng)的類型中有沒有實現(xiàn)運算符對應(yīng)的方法

# 10 + 20    # 10.__add__(20)
# 'abc' + '123'    # 'abc'.__add__('123')
# 100 - 10    # 100.__sub__(10)




class Person:
    def __init__(self,name='',age=0):
        self.name = name
        self.age = age


    def __add__(self, other):
        return self.age + other.age


    def __mul__(self, other):
        list1 = []
        for _ in range (other):
            list1.append(copy(self))
        return list1

# 大于和小于符號實現(xiàn)任意一個,另一個也可以用
    def __lt__(self,other):
        return self.age < other.age


    def __repr__(self):
        return f'{str(self.__dict__)[1:-1]}'


p1 = Person(name='abc',age=18)
p2 = Person(age=238)
print(p1 == p2)


print(p1 + p2)

print(p1 * 3)    # []


persons = [Person('xiaohua',20),Person('xiaoming',19),Person('huahua',21)]
persons.sort()

print(persons)
100>1

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容