我在更广泛的python脚本中使用operator方法时遇到问题。为了缩小问题范围,我创建了以下示例代码。
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'
如何解决第一个对象是浮点数时出现的问题?
答案 0 :(得分:1)
您需要使用反向操作数定义减法(代码本身已修复//您的问题,但可能需要更多清理):
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.
现在你的输出:
const Button& GetObjectBelowMouse(int xMousePos, int yMousePos) // This would be equavalent to your Connect type
{
// all buttons would be your container of buttons / GUI objects.
for( const auto& button : allButtons)
{
// top,bottom,left,right would be the bounding rectangle that encapsulates the coordinates of the object
if( (xMousePos > button.left && xMousePos < button.right ) && (yMousePos > button.bottom && yMousePos < buttom.top))
{
return button;
}
}
// in this case we have a different constructor that creates a "empty" button that has no function
return Button(NO_OBJECT);
}
// the usage would be something like
int main()
{
/*
.. create button, set it's possition, etc
*/
// Option 1
if(GetObjectBelowMouse(mouse.x, mouse.y).type != NO_OBJECT)
{
// Do whatever you want, you know that the user has clicked a valid object
button.Foo();
}
// Option 2
GetObjectBelowMouse(mouse.x, mouse.y).Foo(); // You know that every button has a foo object, and that NO_OBJECT has a foo that does nothing, so you don't need to compare if it is NO_OBJECT or not.
}
答案 1 :(得分:1)
对于您的具体问题并不是真正的答案,但将实际的速度减去速度,而不是汽车会更简单,更简洁>到速度。
只需car1.Speed() - car2.Speed()
或car2.Speed() - 6.0
即可。否则你会创建自己的问题。
作为附注,我还建议您遵循Python样式指南https://www.python.org/dev/peps/pep-0008/