我刚刚开始学习Python,在调用类时遇到了困难。我在使用代码。我查过错误,但找不到任何有用的东西。到目前为止,我所有的经验都是关于Java的,并且认为我可能搞混了一些东西。任何帮助都将不胜感激!
print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
if dotheywantotplay == "y":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
personchoice1 = input("What move will you do? [\"Rock\", \"Paper\", \"Scissors\"]")
personchoice2 = input("What move will you do? [\"Rock\", \"Paper\", \"Scissors\"]")
Play(personchoice1,personchoice2) // The error looks like its this line
else:
print("I am so sad now :-(")
exit()
class Play:
def __init__(player1, player2):
if player1 == player2:
print("Tie!")
elif player1 == "Rock":
if player2 == "Paper":
print("You lose!", player2, "covers", player1)
else:
print("You win!", player1, "smashes", player2)
elif player1 == "Paper":
if player2 == "Scissors":
print("You lose!", player2, "cut", player1)
else:
print("You win!", player1, "covers", player2)
elif player1 == "Scissors":
if player2 == "Rock":
print("You lose...", player2, "smashes", player1)
else:
print("You win!", player1, "cut", player2)
else:
print("That's not a valid play. Check your spelling!")以上是供今后参考的原始问题。以下是解决办法。Python与Java不同,因为在引用类之前,必须先定义它们。这意味着类必须位于python文件的顶部。希望这能帮助其他Java书呆子尝试用Python编写程序..。

print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
class Play:
def __init__(self, player1, player2, name1, name2 ):
self.player1 = player1
self.player2 = player2
self.name1 = name1
self.name2 = name2
if player1 == player2:
print("Tie!")
elif player1 == "Rock":
if player2 == "Paper":
print("You Win ", name2,"!")
print(player2, "covers", player1)
else:
print("You Win ", name1,"!")
print(player1, "smashes", player2)
elif player1 == "Paper":
if player2 == "Scissors":
print("You Win ", name2,"!")
print(player2, "cut", player1)
else:
print("You Win ", name1,"!")
print(player1, "covers", player2)
elif player1 == "Scissors":
if player2 == "Rock":
print("You Win ", name2,"!")
print(player2, "smashes", player1)
else:
print("You Win ", name1,"!")
print(player1, "cut", player2)
else:
print("That's not a valid play. Check your spelling!")
if dotheywantotplay == "y":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
personchoice1 = input("What move will you do? \"Rock\", \"Paper\", \"Scissors\" ")
personchoice2 = input("What move will you do? \"Rock\", \"Paper\", \"Scissors\" ")
Play(personchoice1,personchoice2, player1, player2)
else:
print("I am sad now :-(")
exit()发布于 2020-11-25 20:16:27
Python是从上到下执行的,因此您的所有类和finctions都应该在调用之前定义(所以放在顶部)。也是
class Play:
def __init__(player1, player2):
self.player1 = player1
self.player2 = player2您应该像这样在类中定义属性,在此之前,self引用类的当前实例,这里中的所有内容。
https://stackoverflow.com/questions/65011428
复制相似问题