添加两个compex数字

时间:2015-05-27 02:22:48

标签: python

以下是我编写的用于添加两个复数的代码。我没有包括复数的“i”部分。代码不会返回add方法。

import math
class complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary  

    def __add__(self, other): 
        return complex(self.real + other.real, self.imaginary + other.imaginary)

L1 = [map(float, raw_input().split())]
L2 = [map(float, raw_input().split())]
z1 = complex(L1[0][0],L1[0][1])
z2 = complex(L2[0][0],L2[0][1])
print z1.real, z1.imaginary, z2.real, z2.imaginary
print z1+z2

代码正确打印z1.real,z1.imaginary,z2.real,z2.imaginary变量。但是,当我尝试添加z1 + z2时,它不会返回任何内容。

示例输入:

2 1
5 6

示例输出:

2.0 1.0 5.0 6.0
<__main__.complex object at 0x7fa11c039790>

请让我知道我在做错误的地方

2 个答案:

答案 0 :(得分:4)

您的代码实际上正在运行。当您print z1+z2时,它会打印出正确的对象。你可以验证:

print (z1+z2).real, (z1+z2).imaginary

问题在于,当你只是print z1+z2时,对象的打印方式是这样的:

<__main__.complex object at 0x7fa11c039790>

这不是很有用。但Python无法猜出你希望你的类型的实例看起来像什么;你必须告诉它。

有两种方法,__str____repr__。如果您必须有一个表示最终用户可读输出,另一个表示调试,您可以定义两个;否则,只需定义__repr__

例如:

class complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary  

    def __add__(self, other): 
        return complex(self.real + other.real, self.imaginary + other.imaginary)

    def __str__(self):
        return '{}, {}'.format(self.real, self.imaginary)

    def __repr__(self):
        return 'complex({}, {})'.format(self.real, self.imaginary)

Python 3.x添加了一些工具,让您更轻松;特别是,SimpleNamespace负责处理简单类的基本__init____repr__,因此您只需编写__add__。但是如果您使用的是Python 2.7,那些工具就不存在了。

答案 1 :(得分:2)

有效。 (我打电话给你的班级Complex2,不要屏蔽内置的complex。)

>>> res = Complex2(1, 3) + Complex2(3, 4)
>>> res.real
4
>>> res.imaginary
7
>>> print(res)
<__main__.Complex2 object at 0x10c321a58>

最后一个输出是您实例的表示。

添加方法__repr__以查看有用的输出:

class Complex2(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary  

    def __add__(self, other): 
        return Complex2(self.real + other.real, self.imaginary + other.imaginary)

    def __repr__(self):
        return '({}+{}j)'.format(self.real, self.imaginary) 

现在:

print(res)

所示:

(4+7j)

对于实际工作,请使用内置complex。文字:

>>> 1 + 3 + 3 + 4j
(7+4j)

或明确创建新对象:

>>> complex(5)
(5+0j)
相关问题