请给我Python。你知道吗
我想问的是,如何创建抽象对象(如“石头、布、剪刀”),并直接比较它们?你知道吗
谢谢。你知道吗
#class Weapon:
# pass
#rock = Weapon()
编辑时间:
抱歉问了个坏问题。我没说清楚。 我想要一些这样的代码:
class Weapon():
def __init__(self, agr1[, agr2]):
self.agr1 = agr1
#self.agr2 = agr2
def __cmp__(self, other):
#if some condition:
return -1
#if self == other:
return 0
#if some condition:
return 1
rock = Weapon(arg1, arg2)
scissors = Weapon(arg1, arg2)
#When it's done. It should look like this:
>>>rock > scissors
True
要实现自定义类之间的比较,需要实现comparison magic methods,例如:
但是,如果您的类没有属性,那么您实际上是在尝试比较类实例分配给的名称,这是没有意义的。相反,重构类:
现在你可以制造武器了
Python类具有内置的方法
__eq__
,在比较2类对象时调用该方法。你知道吗必须重写此方法并检查要比较的值。你知道吗
相关问题 更多 >
编程相关推荐