Reputation: 68
Trying to make a board, which must be a square if there as only one argument (and a rectangle if there are two of them).
Code sample:
class Game:
def __init__(self,h,w=h): # lookie-lookie
self.board = [[0 for i in range(w)] for j in range(h)]
What I expect:
b = Game(2)
b.board
#should return [[0,0],[0,0]]
b = Game(2,1)
b.board
#should return [[0],[0]]
What i got:
NameError: name 'h' is not defined
How should I fix it?
Upvotes: 1
Views: 40
Reputation: 78546
At function definition, the value passed to optional arguments is evaluated, however, in that instant, h
is not defined. You can instead use a sentinel value as a placeholder for the optional argument:
class Game(object):
def __init__(self,h,w=None):
if w is None:
w = h
If you're on Python 2, remember to subclass object
.
Upvotes: 3