我想要的是用裝飾器在兩個物件之間進行比較。像這樣的東西
@some_decorator
class SomeClass:
def __init__(self, value):
self.value = value
s1 = SomeClass(10)
s2 = SomeClass(5)
print(s1 > s2) # True
我知道魔術方法。我只是好奇這是否真的有可能
uj5u.com熱心網友回復:
您可以在裝飾器函式中定義一對比較函式,然后將它們添加到類中。要獲取引數,您可以包裝函式。Usingfunctools.total_ordering是一種添加其他比較函式的便捷方法,無需將它們全部寫出來(如果這很重要,請注意檔案中關于性能的警告)。
from functools import total_ordering
def compare(attribute):
def deco(klass):
def __eq__(self, other):
if isinstance(other, klass):
return getattr(self, attribute) == getattr(other, attribute)
else:
return NotImplemented
def __gt__(self, other):
if isinstance(other, klass):
return getattr(self, attribute) > getattr(other, attribute)
else:
return NotImplemented
klass.__eq__ = __eq__
klass.__gt__ = __gt__
return total_ordering(klass)
return deco
@compare('value')
class SomeClass():
def __init__(self, value):
self.value = value
s1 = SomeClass(10)
s2 = SomeClass(5)
print(s1 > s2) # True
print(s1 >= s2) # True
print(s1 < s2) # False
print(s1 <= s2) # False
print(s1 == s2) # False
print(s1 != s2) # True
正如@juanpa.arrivillaga 在評論中建議的那樣,這會檢查實體,因此如下比較的行為符合預期:
s1 > 50
# TypeError: '>' not supported between instances of 'SomeClass' and 'int'
而不是更令人困惑的:AttributeError: 'int' object has no attribute 'value'
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512811.html
上一篇:按多列分組陣列
