[英]PYTHON: AttributeError: 'int' object has no attribute 'hand'
So I have an exercise on python - building a BlackJack game. 因此,我在python上进行了练习-构建BlackJack游戏。 I have started with defining how every phrase of the game would go.
我首先定义了游戏中的每个短语。 Now when I run this code below, In case the input is '0' - which means you don't want cards anymore, it runs perfectly.
现在,当我在下面运行此代码时,如果输入为“ 0”-这意味着您不再需要卡片,它将完美运行。 But when the input is '1' - which means you want to pick card, I get an error:
但是,当输入为'1'时-这意味着您要选择卡片,我会收到一条错误消息:
Traceback (most recent call last):
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 1, in <module>
class blackjack(object):
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 34, in blackjack
player(1)
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 25, in player
PickCard(1)
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 18, in PickCard
self.hand+= random.randrange(1, 13)
AttributeError: 'int' object has no attribute 'hand'
The code: 编码:
class blackjack(object):
#this func defines how player should react
def player(self):
#this func defines what case of technical loosing
def loser():
print("You have reached", hand , ". Which is beyond 21. Therefor, you have lost the game. Better luck next time!")
#this func is responsible for picking card issue.
def PickCard(self):
import random
x=1
while x == 1:
pick = int(raw_input("Enter 1 if you want another card, else Enter 0"))
if pick == 1:
self.hand = self.hand + random.randrange(1, 13)
else:
x=0
import random
print "Now your first card will automatically be given to you:"
hand=random.randrange(1,13)
print "hand: ", hand
PickCard(1)
print hand
if hand>21:
loser()
elif hand==21:
pass
else:
pass
player(1)
Thanks in advance. 提前致谢。
You are making the function call as player(1)
where the player
function expects the argument as of self
type .ie instance of the class blackjack
. 您正在以
player(1)
形式进行函数调用,其中player
函数期望参数的类型为self
类型,即blackjack
类的实例。 Hence, while doing self.hand = self.hand + random.randrange(1, 13)
it is throwing the above mentioned error. 因此,在执行
self.hand = self.hand + random.randrange(1, 13)
,会抛出上述错误。
I think you do not want to make a call to player()
function from within the class, Is it? 我认为您不想从类中调用
player()
函数,是吗? Move that part to outside the class. 将该部分移到班外。 Firstly create the object of class
blackjack
(Note: In Python, class names should be defined as CamelCase variables like: BlackJack). 首先创建类
blackjack
的对象(注意:在Python中,类名称应定义为CamelCase变量,例如:BlackJack)。 For example: 例如:
blackjack_obj = blackjack()
Then call the player()
function as: 然后按以下方式调用
player()
函数:
blackjack_obj.player()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.