3 回答

TA貢獻1864條經(jīng)驗 獲得超6個贊
這可以使用描述符來完成。以下類使用在類體內(nèi)實例化該類時具有特殊效果的特殊方法。
class SuperCaller:
def __set_name__(self, owner, name):
"""Called when the class is defined. owner is the class that's being
defined. name is the name of the method that's being defined.
"""
method = getattr(super(owner, owner), name)
def call(self, other):
# Note that this self shadows the __set_name__ self. They are two
# different things.
return type(self)(method(self, other))
self._call = call
def __get__(self, instance, owner):
"""instance is an instance of owner."""
return lambda other: self._call(instance, other)
class A(int):
__add__ = SuperCaller()
x = A()
print(type(x + 1))
輸出:<class '__main__.A'>

TA貢獻1841條經(jīng)驗 獲得超3個贊
一種方法是創(chuàng)建一個裝飾器,它可以用強制轉換包裝所需的數(shù)學運算:
def wrap_math(c):
def wrapped(orig):
return lambda s, o: c(orig(s,o))
maths = ["__add__", "__sub__"]
for op in maths:
func = wrapped(getattr(c, op))
setattr(c, op, func)
return c
@wrap_math
class Special(int)
pass
x = Special(10)
type(x + 10)
完成您要包裝的功能列表,您應該一切順利。一種方法是創(chuàng)建一個裝飾器,它可以用強制轉換包裝所需的數(shù)學運算:
def wrap_math(c):
def wrapped(orig):
return lambda s, o: c(orig(s,o))
maths = ["__add__", "__sub__"]
for op in maths:
func = wrapped(getattr(c, op))
setattr(c, op, func)
return c
@wrap_math
class Special(int)
pass
x = Special(10)
type(x + 10)
完成您要包裝的功能列表,您應該一切順利。

TA貢獻1827條經(jīng)驗 獲得超8個贊
該super()函數(shù)從父類調用方法,int在這種情況下。相反,您應該在方法中初始化類__add__:
class A(int):
def __add__(self, number):
return A(self.numerator + number)
x = A(4)
print(type(x + 1))
添加回答
舉報