gpt4 book ai didi

Python 类 % 运算符重载

转载 作者:行者123 更新时间:2023-11-30 23:21:00 25 4
gpt4 key购买 nike

我有一组计算不同数字特征的函数(例如名为calculate),但其中一些可能无法正确计算。计算结果将以字符串格式打印在图形用户界面中。所以我想返回一个特殊类的对象,它可以格式化为浮点但返回常量值,例如不适用(_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__ 方法的内容,但我不想使用新式格式,因为在我看来它太复杂且难以阅读。

最佳答案

简短回答:您应该引发(而不是返回)错误,并且它们应该继承自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 风格的字符串格式;唯一的异常(exception)是 '%s' 将调用 __str__,您可以实现它,但您肯定不能给出非float作为 '%f' 的值。相比之下,你完全可以用 str.format 搞乱:

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


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

编辑:正如 Martijn 在评论中指出的那样,您可以实现 __float__ 来为 '%f'< 提供值,但这必须返回一个 float

关于Python 类 % 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25139214/

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