【问题标题】:Automatic conversion to user define type in Python在 Python 中自动转换为用户定义类型
【发布时间】:2016-12-16 11:08:41
【问题描述】:

我正在构建一个类型 (dual numbers),但找不到让它们在算术表达式中表现良好的方法,就像 Python 中的复数一样:

>>> 2 + 3 + 7j
>>> 5 + 7j

就我而言:

>>> 3 + 4 + 5e
>>> obvious type error

我可以很容易地让它工作,操纵 __add__ 方法,另一种方式:我的类型 + 内置。我也可以通过外部函数添加和传递参数来做到这一点,但显然,与 '+' 的良好集成是好多了。
提前致谢。 PS 在哪里可以找到 Python 模块源代码(我可以自己查看一个复杂的类)?

【问题讨论】:

  • 检查__radd__
  • @niemmi:这看起来不错,会检查一下。
  • @niemmi:这很酷,只需检查一下,适用于加法,还有一些非对称操作的技巧!

标签: python class python-3.4 arithmetic-expressions


【解决方案1】:

在 Python 中没有自动类型转换为用户定义的类型。

你需要实现_add____radd____sub____rsub__等方法来模拟数字类型的行为。

请参阅the Language Reference 了解您需要实现的魔法方法列表。

您可以在https://hg.python.org/找到CPython的源代码。

【讨论】:

    【解决方案2】:

    不确定你能做到这一点。这些被称为内置类型,您无法扩展它们。但是,您可以这样做:

    class ENumber():
         def __init__(self, a=0, b=0):
             self.a = a
             self.b = b
    
         def __repr__(self):
             return "{} + {}e".format(self.a, self.b)
    
         def __add__(self, other):
             if isinstance(other, ENumber):
                 return ENumber(self.a + other.a, self.b + other.b)
    

    实际操作:

    In [15]: x = ENumber(1, 1)
    
    In [16]: y = ENumber(2, 2)
    
    In [17]: x+y
    Out[17]: 3 + 3e
    

    当然,您还必须实现所有其他重要功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 2023-03-11
      • 2022-01-22
      • 2011-04-02
      • 2012-06-10
      • 1970-01-01
      相关资源
      最近更新 更多