Python类百分号运算符重载

2024-04-23 07:13:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组函数可以计算不同的数字特征(例如calculate),但其中一些函数可能无法正确计算。计算结果将以字符串格式打印在图形用户界面上。因此,我想返回一个特殊类的对象,它可以格式化为float,但返回常量值,例如N/A(_WrongCalculationError)。Python中有没有什么神奇的方法可以使用旧式格式来实现这一点?你知道吗

class _WrongCalculationError(object):
    def __??????__(self):
        return "N/A"

WrongCalculationError = _WrongCalculationError()

def calculate(x, y):
    if x == y:
        return WrongCalculationError
    else:
        return x/y

 def main(*args):
     print("Calculation result is: %.3f" % calculate(args[0], args[1])

我读过__format__方法,但我不想使用新样式的格式,因为在我看来,它太复杂,很难阅读。你知道吗


Tags: 对象方法函数字符串returndef格式args
1条回答
网友
1楼 · 发布于 2024-04-23 07:13:18

简短回答:您应该raise(而不是return)错误,它们应该从Exception继承:

class WrongCalculationError(Exception):
    pass

def calculate(x, y):
    if x == y:
        raise WrongCalculationError
    return x / y

然后你可以像这样处理它们:

try:
    print("Calculation result is: %.3f" % calculate(args[0], args[1]))
except WrongCalculationError:
    print("Oops!")

长答案:%的“神奇方法”是__mod____rmod____imod__

>>> class Test(object):
    def __mod__(self, other):
        print "foo:", other


>>> t = Test()
>>> t % "bar"
foo: bar

然而,这实际上只是一个语法黑客;它看起来有点像C样式的字符串格式。如果要将自定义对象作为value传递到%(即在右侧),则此操作将不起作用;__rmod__与^{不同相同:

>>> class Test(object):
    def __rmod__(self, other):
        raise Exception


>>> t = Test()
>>> "bar %s" % t
'bar <__main__.Test object at 0x030A0950>'
>>> "bar %f" % t

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    "bar %f" % t
TypeError: float argument required, not Test

请注意:

  1. __rmod__从未被调用;并且
  2. TypeError发生在'%f'转换规范上。你知道吗

您不能自定义C样式的字符串格式;唯一的例外是'%s'将调用__str__,您可以实现它,但您肯定不能将非float作为'%f'的值。相比之下,你完全可以乱搞str.format

>>> class Test(object):
    def __format__(self, spec):
        return "hello!"


>>> "{0:03f}".format(Test())
'hello!'

编辑:正如Martijn在评论中指出的那样,您可以实现__float__以向'%f'提供一个值,但是这个必须返回一个float。你知道吗

相关问题 更多 >