[英]Function not Defined in Class
I am having trouble with a coding project in which I am trying to use classes in python to make a card game (cheat).我在尝试使用 python 中的类来制作纸牌游戏(作弊)的编码项目时遇到问题。 However, when creating the player class, one of the functions that was previously defined within the class is shown as undefined.
但是,在创建播放器 class 时,之前在 class 中定义的函数之一显示为未定义。 I cannot figure out the reason, and any suggestion is appreciated.
我无法弄清楚原因,任何建议都值得赞赏。 Below is the definition of the classes
下面是类的定义
class card(object):
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
class player(object):
def __init__ (self):
self.number = number
self.hand = list()
#Here, hand is a list of the card class that was distributed with a suit and a rank
def check_card(self,player_rank,player_suit):
for card in self.hand:
if card.rank == player_rank and card.suit == player_suit:
return True
break
return False
def play_card(self):
suit = input('what is the suit?')
rank = input('what is the rank?')
if check_card(self,rank,suit):
print(True)
else:
print(False)
Here is the actual code that will run it这是将运行它的实际代码
player = player()
player.play_card()
The following error was received:收到以下错误:
NameError: name 'check_card' is not defined
I have been troubleshooting and looking at different solutions, including moving the functions outside the class, but it continues to display the same error.我一直在排除故障并查看不同的解决方案,包括将功能移到 class 之外,但它继续显示相同的错误。 Can anyone point out the mistake?
谁能指出错误? Thanks!
谢谢!
You have the following two issues in your code您的代码中有以下两个问题
check_card
function is wrong.check_card
function 的方式是错误的。 You must call it in this wayself.check_card(rank,suit)
This is the corrected code:这是更正后的代码:
class card(object):
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
class player(object):
def __init__ (self, number):
self.number = number
self.hand = list()
#Here, hand is a list of the card class that was distributed with a suit and a rank
def check_card(self,player_rank,player_suit):
for card in self.hand:
if card.rank == player_rank and card.suit == player_suit:
return True
break
return False
def play_card(self):
suit = input('what is the suit?')
rank = input('what is the rank?')
if self.check_card(rank,suit):
print(True)
else:
print(False)
player = player(3)
player.play_card()
Output: Output:
what is the suit?spade
what is the rank?3
False
Based on this document the function call in python class is self.xxxx(args) (xxxx is denoted function name) therefore the correct version of play_card function is shown as following. Based on this document the function call in python class is self.xxxx(args) (xxxx is denoted function name) therefore the correct version of play_card function is shown as following.
enter code here
def play_card(self):
suit = input('what is the suit?')
rank = input('what is the rank?')
if self.check_card(rank,suit):
print(True)
else:
print(False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.