本文介绍了尝试重载运算符"/"时发生错误.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始自学游戏编程.有人建议我从Python入手,然后得到一本书从Python和Pygame开始游戏开发:从新手到专业人员".我参加了一部分,他们讲授有关Vectors的知识并创建Vector2类.一切都进行得很好,直到我尝试让除法运算符超载.我的代码是这样的:

I recently start teaching myself game programming. Someone recommend me to start with Python and I got the book "Beginning game development with Python and Pygame: From novice to professional". I got to a part where they teach about Vectors and creating a Vector2 class. Everything was going well until I tried to overload the division operator.My code goes like this:

class Vector2(object):

  def __init__(self, x=0.0, y=0.0):
    self.x = x
    self.y = y

  def __str__(self):
    return "(%s, %s)"%(self.x, self.y)

  @classmethod
  def from_points(cls, P1, P2):
    return cls(P2[0] - P1[0], P2[1] - P1[1])

  def __add__(self,rhs):
    return Vector2(self.x + rhs.x, self.y + rhs.y)

  def __sub__(self,rhs):
    return Vector2(self.x - rhs.x, self.y - rhs.y)

  def __mul__(self, scalar):
    return Vector2( self.x*scalar, self.y*scalar)

  def __div__(self, scalar):
    return Vector2( self.x/scalar, self.y/scalar)

现在,当我尝试调用"/"运算符时,将显示:

Now, when I tried to call the "/" operator, this shows up:

AB = Vector2(10.0,25.0)
print(AB)   # <<<<(10.0, 25.0)
v1 = AB + Vector2(20.,10.)
print(v1)   # <<<<(30.0, 35.0)
v2 = AB - Vector2(20.,10.)
print(v2)   # <<<<(-10.0, 15.0)
v3 = AB * 3
print(v3)   # <<<<(30.0, 75.0)
print(v3 / 3)
TypeError: unsupported operand type(s) for /: 'Vector2' and 'int'

这一切都在Python 3.3中实现,但是如果我在Python 2.7中运行它,一切都将正常运行.哪里出问题了?

This was all in Python 3.3 but if I run it with Python 2.7, everything works correctly.Where's the problem?

推荐答案

在Python 3.x中,您需要重载__floordiv____truediv__运算符,而不是__div__运算符.前者对应于//操作(返回整数),而后者对应于/(返回浮点数).

In Python 3.x, you need to overload the __floordiv__ and __truediv__ operators, not the __div__ operator. The former corresponds to the // operation (returns an integer) and the latter to / (returns a float).

这篇关于尝试重载运算符"/"时发生错误.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:27