I am having an issue in Python with using a class instance attribute as the default value of a method parameter. Let me show you the code which is spitting out an error:
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
human
is a instance of a Player
class and I use the attribute human.bet
in other methods in this Table
class perfectly fine. No instance of the Table
class is called before human
is defined, is there a way to use an attribute in this way?
CodePudding user response:
Your code will always raise NameError until name 'human' is present in the same scope where class table is defined (before table class definition). You can add name by importing it or defining it in the same module.
from some_module import human
class Table():
def print_table(self,message = f'Current bet: {human.bet}'):
or
human = Player()
class Table():
def print_table(self,message = f'Current bet: {human.bet}'):
Anyways its a bad dependency.