【发布时间】:2022-07-11 23:53:12
【问题描述】:
我在 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)
我的错误是:
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
human 是Player 类的一个实例,我在这个Table 类的其他方法中使用属性human.bet 非常好。在定义human之前没有调用Table类的实例,有没有办法以这种方式使用属性?
【问题讨论】:
-
human需要在类定义时定义。显然不是。只需使用= None作为占位符并在函数体中检查它。 - “在定义人类之前没有调用 Table 类的实例” - 是的,但是如果human没有定义,那么该类甚至不能被定义,就像你一样将其用作其方法之一的定义的一部分。 -
human的确切定义在哪里?请提供minimal reproducible example。我想发布一个答案,但没有上下文,很难给出好的建议。不过 Marco 可能是对的,您可能应该使用=None作为标记值。
标签: python class parameter-passing