gpt4 book ai didi

python - Python 中是否有可能使用 "catch"魔术方法?

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:21 25 4
gpt4 key购买 nike

灵感来自 this question ,我认为将一个“MutableNum”类放在一起会很有趣,在尽可能多的情况下,它的行为就像标准数字类型一样,但它是可变的,所以像下面这样的东西会起作用:

def double(x): x *= 2

x = MutableNum(9)
print(x) # 9
double(x)
print(x) # 18

我得到了以下内容:

class MutableNum():
val = None
def __init__(self, v): self.val = v
# Comparison Methods
def __eq__(self, x): return self.val == x
def __ne__(self, x): return self.val != x
def __lt__(self, x): return self.val < x
def __gt__(self, x): return self.val > x
def __le__(self, x): return self.val <= x
def __ge__(self, x): return self.val >= x
# Arithmetic
def __mul__(self, x): return self.__class__(self.val * x)
def __rmul__(self, x): return self.__class__(self.val * x)
# Casts
def __int__(self): return self.val
# Represenation
def __str__(self): return "%d" % (self.val)
def __repr__(self): return "%s(%d)" % (self.__class__.__name__, self.val)

这是可行的(据我所知,到目前为止),但我发现自己想要“捕获”神奇的方法,因为它们中的许多都遵循非常相似的结构。

例如,我想像这样捕获 __mul____add____sub__ 等:

def catch(self, method, x): return MutableNum(self.val.method(x))

所以对于 __add__catch() 会返回

return MutableNum(self.val.__add__(x))

这样的事情可能吗?或者我应该像我已经完成的那样实现所有魔术方法?

编辑:我尝试了一些尝试使用 __getattr__(self,key) 捕捉魔术方法,但我得到的结果好坏参半。

提前致谢。

编辑2

在大家的帮助下,我得出了以下结论:

class MutableNum(object):
__val__ = None
def __init__(self, v): self.__val__ = v
# Comparison Methods
def __eq__(self, x): return self.__val__ == x
def __ne__(self, x): return self.__val__ != x
def __lt__(self, x): return self.__val__ < x
def __gt__(self, x): return self.__val__ > x
def __le__(self, x): return self.__val__ <= x
def __ge__(self, x): return self.__val__ >= x
def __cmp__(self, x): return 0 if self.__val__ == x else 1 if self.__val__ > 0 else -1
# Unary Ops
def __pos__(self): return self.__class__(+self.__val__)
def __neg__(self): return self.__class__(-self.__val__)
def __abs__(self): return self.__class__(abs(self.__val__))
# Bitwise Unary Ops
def __invert__(self): return self.__class__(~self.__val__)
# Arithmetic Binary Ops
def __add__(self, x): return self.__class__(self.__val__ + x)
def __sub__(self, x): return self.__class__(self.__val__ - x)
def __mul__(self, x): return self.__class__(self.__val__ * x)
def __div__(self, x): return self.__class__(self.__val__ / x)
def __mod__(self, x): return self.__class__(self.__val__ % x)
def __pow__(self, x): return self.__class__(self.__val__ ** x)
def __floordiv__(self, x): return self.__class__(self.__val__ // x)
def __divmod__(self, x): return self.__class__(divmod(self.__val__, x))
def __truediv__(self, x): return self.__class__(self.__val__.__truediv__(x))
# Reflected Arithmetic Binary Ops
def __radd__(self, x): return self.__class__(x + self.__val__)
def __rsub__(self, x): return self.__class__(x - self.__val__)
def __rmul__(self, x): return self.__class__(x * self.__val__)
def __rdiv__(self, x): return self.__class__(x / self.__val__)
def __rmod__(self, x): return self.__class__(x % self.__val__)
def __rpow__(self, x): return self.__class__(x ** self.__val__)
def __rfloordiv__(self, x): return self.__class__(x // self.__val__)
def __rdivmod__(self, x): return self.__class__(divmod(x, self.__val__))
def __rtruediv__(self, x): return self.__class__(x.__truediv__(self.__val__))
# Bitwise Binary Ops
def __and__(self, x): return self.__class__(self.__val__ & x)
def __or__(self, x): return self.__class__(self.__val__ | x)
def __xor__(self, x): return self.__class__(self.__val__ ^ x)
def __lshift__(self, x): return self.__class__(self.__val__ << x)
def __rshift__(self, x): return self.__class__(self.__val__ >> x)
# Reflected Bitwise Binary Ops
def __rand__(self, x): return self.__class__(x & self.__val__)
def __ror__(self, x): return self.__class__(x | self.__val__)
def __rxor__(self, x): return self.__class__(x ^ self.__val__)
def __rlshift__(self, x): return self.__class__(x << self.__val__)
def __rrshift__(self, x): return self.__class__(x >> self.__val__)
# Compound Assignment
def __iadd__(self, x): self.__val__ += x; return self
def __isub__(self, x): self.__val__ -= x; return self
def __imul__(self, x): self.__val__ *= x; return self
def __idiv__(self, x): self.__val__ /= x; return self
def __imod__(self, x): self.__val__ %= x; return self
def __ipow__(self, x): self.__val__ **= x; return self
# Casts
def __nonzero__(self): return self.__val__ != 0
def __int__(self): return self.__val__.__int__() # XXX
def __float__(self): return self.__val__.__float__() # XXX
def __long__(self): return self.__val__.__long__() # XXX
# Conversions
def __oct__(self): return self.__val__.__oct__() # XXX
def __hex__(self): return self.__val__.__hex__() # XXX
def __str__(self): return self.__val__.__str__() # XXX
# Random Ops
def __index__(self): return self.__val__.__index__() # XXX
def __trunc__(self): return self.__val__.__trunc__() # XXX
def __coerce__(self, x): return self.__val__.__coerce__(x)
# Represenation
def __repr__(self): return "%s(%d)" % (self.__class__.__name__, self.__val__)
# Define innertype, a function that returns the type of the inner value self.__val__
def innertype(self): return type(self.__val__)
# Define set, a function that you can use to set the value of the instance
def set(self, x):
if isinstance(x, (int, long, float)): self.__val__ = x
elif isinstance(x, self.__class__): self.__val__ = x.__val__
else: raise TypeError("expected a numeric type")
# Pass anything else along to self.__val__
def __getattr__(self, attr):
print("getattr: " + attr)
return getattr(self.__val__, attr)

我放了整个类,带有用法标题和粗略的测试套件 here .

mgilson 关于使用 @total_ordering 的建议会稍微简化这一点。

只要您遵循使用指南(例如,使用 x *= 2 而不是 x = x * 2),看起来您会没事的。

虽然,简单地将参数包装在一个列表中然后修改 x[0] 似乎容易得多 -- 仍然是一个有趣的项目。

最佳答案

最简单的事情就是手动实现它们。如果这是你要添加到很多类中的东西,那么你可能会看看元类(可能是大脑融化)或类装饰器(更容易处理),但你应该手工完成一次,这样你就知道发生了什么.

__getattr__ 只在某些时候起作用的原因是只有当它正在查找的名称在类或其任何基类 上找不到时才会被调用。因此,如果可以在 object 上找到 __xyz__,则不会调用 __getattr__

关于python - Python 中是否有可能使用 "catch"魔术方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18938755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com