Reputation: 564
As a new user of Python, I try to code a program to learn how to use class. This is what I got so far in my Game class
class Game(Table):
def __init__(self):
super().__init__(21, 10)
self.reset()
def __str__(self):
return makeGrid(self)
def reset(self):
self.setValues(' ' for _ in range(210))
for v in range(10):
self[10, v]='+'
def Startup(self):
p1=input('Player 1 name: ')
p2=input('Player 2 name: ')
def p1turn(self):
print('r%, its your turn!'% p1)
My problem is that I want to use the p1 and p2 variables in some other function, but I realised that I can't access to a variable in a function and use it in an other function. ( In this case, if I try to run my p1turn(), I got an error because p1 does not exist.
Upvotes: 1
Views: 53
Reputation: 168876
In each function, the first reference passed in (conventionally bound to the name self
) is a reference to the instance object of this class. One may store values as attributes of that instance.
Practically speaking, put self.
in front of any variables that you want to share between methods, like so:
def Startup(self):
self.p1=input('Player 1 name: ')
self.p2=input('Player 2 name: ')
def p1turn(self):
print('r%, its your turn!'% self.p1)
Upvotes: 2