【发布时间】:2020-05-20 16:17:55
【问题描述】:
我正在努力熟悉 python。为此,我正在开发一个石头、纸、剪刀游戏。我有一个类来处理值的比较以确定获胜者。问题是每当我使用重载的大于运算符进行比较时,只有在涉及 rock 时结果才会出错。我做了一个比较方法来测试我的逻辑是否正确。 python中重载运算符的行为是否会导致这种情况?
我的代码:
import random
rock = "rock"
paper = "paper"
scissors = "scissors"
options = (rock, paper, scissors)
class RcpValue:
def __init__(self, value = rock):
self.__value = value
@property
def value(self):
return self.__value
def __eq__(self, other):
if self.__value == other.__value:
return True
return False
def compare(self, other):
if (self.__value == rock) and (other.__value == paper):
return False
if (self.__value == rock) and (other.__value == scissors):
return True
if (self.__value == paper) and (other.__value == scissors):
return False
if (self.__value == paper) and (other.__value == rock):
return True
if (self.__value == scissors) and (other.__value == rock):
return False
if (self.__value == scissors) and (other.__value == paper):
return True
def __gt__(self, other):
if (self.__value == rock) and (other.__value == paper):
return False
if (self.__value == rock) and (other.__value == scissors):
return True
if (self.__value == paper) and (other.__value == scissors):
return False
if (self.__value == paper) and (other.__value == rock):
return True
if (self.__value == scissors) and (other.__value == rock):
return False
if (self.__value == scissors) and (other.__value == paper):
return True
def determine_winner(p1: RcpValue, p2: RcpValue):
if p1.value == p2.value:
return "Tied!"
if p1.value > p2.value:
#if p1.compare(p2):
return "Player 1 wins"
return "Player 2 wins"
def test():
for i in options:
for j in options:
player1 = RcpValue(i)
player2 = RcpValue(j)
print(f"Player 1 chose: {player1.value}")
print(f"Player 2 chose: {player2.value}")
print(determine_winner(player1, player2))
print()
test()
使用__gt__输出:
Player 1 chose: rock
Player 2 chose: rock
Tied!
Player 1 chose: rock
Player 2 chose: paper
Player 1 wins
Player 1 chose: rock
Player 2 chose: scissors
Player 2 wins
Player 1 chose: paper
Player 2 chose: rock
Player 2 wins
Player 1 chose: paper
Player 2 chose: paper
Tied!
Player 1 chose: paper
Player 2 chose: scissors
Player 2 wins
Player 1 chose: scissors
Player 2 chose: rock
Player 1 wins
Player 1 chose: scissors
Player 2 chose: paper
Player 1 wins
Player 1 chose: scissors
Player 2 chose: scissors
Tied!
使用compare() 输出:
Player 1 chose: rock
Player 2 chose: rock
Tied!
Player 1 chose: rock
Player 2 chose: paper
Player 2 wins
Player 1 chose: rock
Player 2 chose: scissors
Player 1 wins
Player 1 chose: paper
Player 2 chose: rock
Player 1 wins
Player 1 chose: paper
Player 2 chose: paper
Tied!
Player 1 chose: paper
Player 2 chose: scissors
Player 2 wins
Player 1 chose: scissors
Player 2 chose: rock
Player 2 wins
Player 1 chose: scissors
Player 2 chose: paper
Player 1 wins
Player 1 chose: scissors
Player 2 chose: scissors
Tied!
【问题讨论】:
标签: python class operator-overloading