2016-12-16 56 views
0

我建立一个类型(dual numbers)定义类型,不能找到让他们很好地表现在算术表达式,像在Python复数的方式做:自动转换为用户在Python

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

在我的情况:

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

我可以很容易使其工作在,操纵__add__method,另一路:我喜欢的类型+内置的我,也能做到这一点,不再需要外接功能添加和传递参数,但是,显然,与'+'的良好整合要好得多。
在此先感谢。 PS哪里可以找到Python模块的源代码(我可以在一个复杂的类自己看)?

+2

检查['__radd__'](https://docs.python.org/3/reference/datamodel.html#object.__radd__) – niemmi

+0

@niemmi:这看起来不错,会检查它。 –

+0

@niemmi:这很酷,只是检查,适用于添加,也有不对称操作的一些技巧! –

回答

0

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

您需要执行方法_add____radd__,__sub____rsub__等来模拟数字类型的行为。

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

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

0

不确定您可以这样做。这些被称为内置类型,并且您无法展开它们。然而,你可以做这样的事情:

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 

当然,你必须实现所有其他显著功能了。