python - 尝试在 Python 中使用运算符方法时出现类型错误

标签 python operators

我在更广泛的 python 脚本中使用运算符方法时遇到问题。为了缩小问题范围,我创建了以下示例代码。

class Car:
   def __init__(self, Name, Speed):
      self.Name = Name
      self.Speed = Speed
      self.PrintText()

   def PrintText(self):
      print("My %s runs %s km/h." % (self.Name, self.Speed))

   def GetName(self):
      return self.Name

   def GetSpeed(self):
      return self.Speed

   def __sub__(self, other):
      try: # Try with assumption that we have to deal with an instance of AnotherClass
         a = self.GetSpeed()
      except: # If it doesn't work let's assume we have to deal with a float
         a = self

      try: # Try with assumption that we have to deal with an instance of AnotherClass
         b = other.GetSpeed()
      except: # If it doesn't work let's assume we have to deal with a float
         b = other

      return a - b

Car1 = Car("VW", 200.0)
Car2 = Car("Trabant", 120.0)
print("")

Difference = Car1 - Car2
print("The speed difference is %g km/h." % Difference)
print("")

Difference = Car2 - 6.0
print("My %s is %g km/h faster than a pedestrian." % (Car2.GetName(), Difference))
print("")

Difference = 250.0 - Car1
print("I wish I had a car that is %g km/h faster than the %s." % (Difference, Car1.GetName()))

输出是:

My VW runs 200.0 km/h.
My Trabant runs 120.0 km/h.

The speed difference is 80 km/h.

My Trabant is 114 km/h faster than a pedestrian.

Traceback (most recent call last):
  File "test.py", line 41, in <module>
    Difference = 250.0 - Car1
TypeError: unsupported operand type(s) for -: 'float' and 'instance'

如何解决当第一个对象是 float 时出现的问题?

最佳答案

您需要使用反转操作数定义减法(代码本身已修复//您的问题,但可能需要更多清理):

   def __rsub__(self, other):
        a = self.GetSpeed()

        try: # Try with assumption that we have to deal with an instance of AnotherClass
         b = other.GetSpeed()
        except AttributeError: # If it doesn't work let's assume we have to deal with a float
         b = other

        return b - a

现在你的输出:

My VW runs 200.0 km/h.
My Trabant runs 120.0 km/h.

The speed difference is 80 km/h.

My Trabant is 114 km/h faster than a pedestrian.

I wish I had a car that is 50 km/h faster than the VW.

关于python - 尝试在 Python 中使用运算符方法时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46429436/

相关文章:

python - 动态改变 scipys ndimage 过滤器中的过滤器大小

java - 从Python服务器到Android客户端的图像数据丢失(Endian问题??)

python - 将错误栏添加到 Matplotlib 生成的 Pandas 数据框图形会创建无效图例

c - 如何使用按位运算符表示否定,C

C# lambda 表达式反向 <=

python - 带有子进程的 Python 和 C++ 程序之间的通信速度非常慢

python - Tensorflow:tf.assign 不分配任何东西

parsing - 左关联运算符与右关联运算符

c++ - 这是获取数字字符列表并使用它们创建长整数的有效方法吗?

ruby - 可以区分 ruby​​ 中的简单运算符和复合赋值运算符之间的歧义吗?