Reputation: 41
I have a python class called Player that looks like this ...
class Player:
def __init__(self):
self.display = 'A'
self.num_water_buckets = 0
self.row = 0
self.col = 0
I am having trouble editing the self.row and self.col ... maybe they're immutable but I haven't found much of this on the internet. Player().row
and Player().col
work, however they print 0 every time. I am trying to edit them using Player().row = value
where value is a variable containing a number.
Thanks in advance!
UPDATE: Okay so I understand that you have to define a new occurrence of this instance using x = Player() then x.row = ...
But I need to originally initialise the variable with certain values (which are different every time) so I thought I could use a function and the return value from that function would set the initial value from the variable but it just creates an infinite recursion. I did...
class Player:
def __init__(self):
from game_parser import read_lines
self.display = 'A'
self.num_water_buckets = 0
self.row = Player().detRow(sys.argv[1])
self.col = Player().detCol(sys.argv[1])
def detRow(fileName):
# use this function to return the row
def detCol(fileName):
# use this function to return the col
Upvotes: 0
Views: 821
Reputation: 2226
You need to add put the variable outside the __init__()
method
EDIT: added row and col to the class
class Player:
row = 0 # NO self here
col = 0
def __init__(self):
self.display = 'A'
self.num_water_buckets = 0
john = Player()
john.num_water_buckets = 12
print(f'before change: {john.col}')
john.col = 5
print(f'after change: {john.col}')
print(f'class property: {Player.col}') # note it did not change the class
Output:
before change: 0
after change: 5
class property: 0
Upvotes: 1
Reputation: 198314
If you do
Player().row = value
print(Player().row)
The Player()
in the first row creates a new instance; then you modify it by setting its row
attribute to value
; then you throw away that instance, because you haven't bothered to remember it anywhere. Then in the next row, you create a new instance (where the initialiser sets the row
attribute to zero).
Not all players are interchangeable. If you sit John in the second row, it does not mean Harry will be in the second row too; it just means John is in the second row.
To do it correctly, store your Player
instance in a variable:
john = Player()
john.row = 2
print(john.row)
Upvotes: 1