[英]Automatic conversion to user define type in Python
我正在建立一个类型( 双数 ),并且找不到使它们在算术表达式中表现良好的方法,就像Python中的复数一样:
>>> 2 + 3 + 7j
>>> 5 + 7j
就我而言:
>>> 3 + 4 + 5e
>>> obvious type error
我可以很容易地使其工作,也可以通过另一种方式来处理__add__方法:我的类型+内置。我也可以使外部函数添加并传递参数,但是显然,与'+'的良好集成要好得多。
提前致谢。 PS在哪里可以找到Python模块源代码(我自己可以看一个复杂的类)?
在Python中,不会自动将类型转换为用户定义的类型。
您需要实现_add__
和__radd__
, __sub__
和__rsub__
等方法,以模拟数字类型的行为。
有关需要实现的魔术方法的列表,请参见语言参考 。
您可以在https://hg.python.org/上找到CPython的源代码。
不确定您可以这样做。 这些称为内置类型,您无法扩展它们。 但是,您可以执行以下操作:
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
当然,您还必须实现所有其他重要功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.