【问题标题】:Why is an instance of my class not being recognised in the method parameters?为什么我的类的实例在方法参数中没有被识别?
【发布时间】: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

humanPlayer 类的一个实例,我在这个Table 类的其他方法中使用属性human.bet 非常好。在定义human之前没有调用Table类的实例,有没有办法以这种方式使用属性?

【问题讨论】:

  • human 需要在类定义时定义。显然不是。只需使用= None 作为占位符并在函数体中检查它。 - “在定义人类之前没有调用 Table 类的实例” - 是的,但是如果 human 没有定义,那么该类甚至不能被定义,就像你一样将其用作其方法之一的定义的一部分。
  • human 的确切定义在哪里?请提供minimal reproducible example。我想发布一个答案,但没有上下文,很难给出好的建议。不过 Marco 可能是对的,您可能应该使用 =None 作为标记值。

标签: python class parameter-passing


【解决方案1】:

您的代码将始终引发 NameError,直到名称“human”出现在定义类表的同一范围内(在表类定义之前)。您可以通过导入或在同一模块中定义来添加名称。

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}'):

无论如何,它是一个糟糕的依赖关系。

【讨论】:

  • 因为是默认参数,所以human也可以定义在类的顶层,只要在print_table之前定义即可。在函数内部你不能做这样的非限定引用,但在默认参数中你可以。
  • 谢谢各位,这回答了我的问题。这是我第一个使用类的项目,所以我对某些事情还是有些摸不着头脑。
猜你喜欢
  • 1970-01-01
  • 2020-11-03
  • 2021-02-22
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2019-12-31
  • 1970-01-01
  • 2011-06-23
相关资源
最近更新 更多