为什么在方法参数中不能识别我的类的实例?



我在Python中有一个问题,使用类实例属性作为方法参数的默认值。让我给你看一下产生错误的代码:

class Table():
# then a bunch of other methods and an __init__
def print_table(self,message = f'Current bet: {human.bet}'):

self.human_cards(human.hold_cards)
self.info_lines(human,cpu,message)
self.cpu_cards(cpu.hold_cards)

for item in self.hum_print:
print(item)
for item in self.info_print:
print(item)
for item in self.cpu_print:
print(item)

my error is:

NameError                                 Traceback (most recent call last)
<ipython-input-7-bf1a6f19a3b1> in <module>
----> 1 class Table():
2 
3 
4     def __init__(self, length, height, card_width = 10, card_spacing = 5):
5         self.length = length
<ipython-input-7-bf1a6f19a3b1> in Table()
44         self.info_print = [line1, line2, line3, line4, line5, line6]
45 
---> 46     def print_table(self,message = f'Current bet: {human.bet}'):
47 
48         self.human_cards(human.hold_cards)
NameError: name 'human' is not defined

humanPlayer类的一个实例,我在这个Table类的其他方法中完全可以使用属性human.bet。在定义human之前,没有Table类的实例被调用,是否有方法以这种方式使用属性?

您的代码将始终引发NameError,直到名称'human'出现在定义类表的相同作用域中(在表类定义之前)。您可以通过导入它或在同一模块中定义它来添加name。

from some_module import human
class Table():
def print_table(self,message = f'Current bet: {human.bet}'):

human = Player()
class Table():
def print_table(self,message = f'Current bet: {human.bet}'):

无论如何,这是一个糟糕的依赖。

最新更新