簡體   English   中英

Python - 將新函數應用於內置類

[英]Python - Applying new functions to builtin classes

我正在使用Python 2.6.6並且我想知道我是否可以將新函數應用於內置類和類型而無需對其進行子類化 ,例如:

t1 = (20,20)
t2 = (40,30)
print t2 - t1 #gives me (20,10)
print t2 + t1 #gives me (60,50)

為此,我需要將__sub__和__add__函數添加到元組類。 可能嗎?

你沒有嚴格的子類,你可以創建一個類並傳入一個元組,確保你也定義了一個__getitem__方法:

class Tuple(object):
    def __init__(self, t):
        self.t = t

    def __getitem__(self, item):
        return self.t[item]

    def __add__(self, other):
        return self[0] + other[0], self[1]+other[1]

    def __sub__(self, other):
        return self[0] - other[0], self[1] - other[1]


t1 = MyTuple((20,20))
t2 = MyTuple((40,30))

print(t2 - t1)
print(t2 + t1)

您不能更改C擴展模塊中定義的任何類型,因為它們是不可變的 ,如果您需要不同的行為,您需要子類或創建自定義類並傳入上述類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM