【问题标题】:Python: Manipulating objects using operator overloadingPython:使用运算符重载操作对象
【发布时间】:2013-04-22 13:09:38
【问题描述】:

我正在尝试创建一个包含两个浮点数的类;一个数据点和一个与该数据点相关的错误。这是我的类定义:

class DataPoint:
def __init__(self, Datum, Error, Operator):
    self.Datum    = Datum
    self.Error    = Error
    self.Operator = Operator
def ReturnDatum(self):
    return self.Datum
def ReturnError(self):
    return self.Error
def ReturnOperator(self):
    return self.Operator

运算符字段只包含一个字符串,对我的问题并不重要。 我现在的目标是能够重载“+”运算符,这样一旦我定义了我的类的两个实例,我就可以简单地使用如下表达式:

    Object3 = Object1 + Object2

其中 Object3 具有 Datum3 = Datum1 + Datum2,以及 Error 的类似简单表达式。我试图通过使用以下函数定义(在我的类定义中)来做到这一点:

def __add__(self, other):
    return DataPoint(self, self.Datum + other.Datum, math.sqrt(self.Error * self.Error + other.Error * other.Error), 'NULL')

但我得到的错误基本上意味着我没有正确定义我的过载。 提前致谢 杰克

编辑:错误是形式上的东西

Traceback (most recent call last):
  File "DataCombination.py", line 78, in <module>
TempObject = LineData[0] - LineData[1]
  File "DataCombination.py", line 22, in __sub__
return DataPoint(self, self.Datum + other.Datum, math.sqrt(self.Error * self.Error + other.Error * other.Error), '+')
TypeError: unsupported operand type(s) for +: 'str' and 'str'

EDIT2:小型可运行示例使用代码:

import math
import sys

# Path to file and filename
FileLocation = 'DataSet.dat'

class DataPoint:
def __init__(self, Datum, Error, Operator):
    self.Datum    = Datum
    self.Error    = Error
    self.Operator = Operator
def __add__(self, other):
    return DataPoint(self.Datum + other.Datum, math.sqrt(self.Error * self.Error + other.Error * other.Error), '+')
def __sub__(self, other):
    return DataPoint(self.Datum - other.Datum, 1.0, 'NULL')
def __mul__(self, other):
    return DataPoint(self.Datum * other.Datum, 1.0, 'NULL')
def __div__(self, other):
    return DataPoint(self.Datum / other.Datum, 1.0, 'NULL')
def ReturnDatum(self):
    return self.Datum
def ReturnError(self):
    return self.Error
def ReturnOperator(self):
    return self.Operator

# Read in the data set from the file
File = open(FileLocation, 'r')
FileSegments = [line.split( ) for line in File.readlines()]

# Clean up the input
for i in xrange(FileSegments.__len__()):
for j in xrange(FileSegments[i].__len__()):
    FileSegments[i][j] = FileSegments[i][j].translate(None, '()')

# Loop over the number lines in the file
for i in xrange(FileSegments.__len__() - 2):

LineData = []

Count = (FileSegments[i].__len__() + 1) / 4

# Import strings into list of objects
for j in xrange((FileSegments[i].__len__() + 1) / 4 - 1):
    x =     j * 4
    y = 2 + j * 4
    z = 3 + j * 4
    LineData.append(DataPoint(FileSegments[i][x], FileSegments[i][y], FileSegments[i][z]))
LineData.append(DataPoint(FileSegments[i][-3], FileSegments[i][-1], 'NULL'))

TempObject = LineData[0] - LineData[1]

示例 DataSet.dat 如下所示:

(-5.63150902306 +/- 0.549562002684) * (9.62647766508 +/- 1.00395610402) + (16.9559698529 +/- 0.507466944938) + (1.07686005998 +/- 0.713190458948)
(9.40128537128 +/- 0.673031987441) * (7.65561264405 +/- 0.11828791914)
(3.19433075143 +/- 1.16442961316) / (8.49485815486 +/- 0.936343018664)

【问题讨论】:

  • 请发布您遇到的错误和一些输入。 self.Datumself.Error 的值是什么?
  • 它们只是浮点数,错误是: Traceback(最近一次调用最后一次):文件“DataCombination.py”,第 78 行,在 TempObject = LineData[0] - LineData[1 ] 文件“DataCombination.py”,第 22 行,在 sub 中返回 DataPoint(self, self.Datum - other.Datum, math.sqrt(self.Error * self.Error + other.Error * other .Error), '+') TypeError: +: 'str' and 'str' 的操作数类型不受支持
  • 请编辑您的问题的信息
  • @JackMedley 在实例化新的DataPoint 时,您不应该传递self
  • 请发布一个可运行的示例。

标签: python oop overloading


【解决方案1】:

第一个错误

试试:

def __add__(self, other):
    return DataPoint(
        self.Datum + other.Datum, 
        math.sqrt(self.Error * self.Error + other.Error * other.Error), 
        'NULL')

请注意,创建新的DataPoint 对象时不必传递“self”。


第二个错误

您使用strs 初始化数据,但您打算使用floats 初始化它们。

试试:

def __init__(self, Datum, Error, Operator):
  self.Datum    = float(Datum)
  self.Error    = float(Error)
  self.Operator = Operator

【讨论】:

  • 虽然,错误似乎发生在之前。否则错误应该是TypeError: __init__() takes exactly 4 arguments (5 given)
  • 我明白了,好的,我已将其删除,但我仍然收到错误消息。我想知道是否应该拥有'self.Datum + other.Datum'而不是'self.ReturnDatum()+ other.ReturnDatum()'
  • 不,不需要更改。我不知道为什么你仍然得到一个错误。当我做出改变时,I don't get the error.。也许您可以将完整简短程序粘贴到您的问题中。
  • @JanneKarila - 刚刚注意到您的评论。您完全正确,之前的错误是 str/float 类型不匹配。
猜你喜欢
  • 2012-05-16
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多