我正在 Jupyter 笔记本中编写 Black Jack 游戏,为此我有一个“玩家”和一个“经销商”类以及一个基本上运行整个游戏的函数 (BlackJack())。
def BlackJack():
name = input("What is your name: ")
while True:
try:
money = int(input(f"Welcome to our casino Black Jack game {name}!How big is your balance in € : "))
except ValueError:
print("Just give me a number: ")
else:
print("Ok, let's start!")
break
player = player(name, money) # player() class
dealer = dealer() # dealer() class
当我尝试创建与类本身同名的类对象时发生错误:
错误信息:
What is your name: "Richard"
Welcome to our casino Black Jack game "Richard"!How big is your balance in € : 19163
Ok, let's start!
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-55-3c92f609e237> in <module>
----> 1 BlackJack()
<ipython-input-54-57fc63786581> in BlackJack()
9 print("Ok, let's start!")
10 break
---> 11 player = player(name, money)
12 dealer = dealer()
UnboundLocalError: local variable 'player' referenced before assignment
但是,如果我将类对象命名为不同的名称或将它们命名为相同的名称,但在函数之外没有错误:
def BlackJack():
name = input("What is your name: ")
while True:
try:
money = int(input(f"Welcome to our casino Black Jack game {name}!How big is your balance in € : "))
except ValueError:
print("Just give me a number: ")
else:
print("Ok, Let's Start!")
break
plyr = player(name, money)
dlr = dealer()
或者
player = player("Jimmy", 1200)
是否只是因为在一个函数中 Python 认为我想在我分配变量之前给它自己分配一个变量 (dealer = Dealer()),即使它们实际上并不相同,因为一个是变量并且其他是类?那么在这种情况下,Python 是否只是忽略了例如dealer() 是一个类而不是变量“dealer”这一事实?
提前致谢!
PS:我使用 Python 3.7.4