Kyle Me
Kyle Me

Reputation: 336

Trouble understanding classes in Python 3. (Maybe a scope issue)

I'm having trouble with understanding classes and the way their scopes work. This is the code that I have now.

class Player():  
    def __init__(self):
        self.wheatFields = 1 #line 3
        self.wheatProduction = self.wheatFields * 10 #line 4

player = Player()
def main(player):
    print('Wheat fields: ' +str(player.wheatFields))
    print('Production: ' +str(player.wheatProduction))
    print('What do you want to do?\n1) Add wheat field')
    if input() == '1':
        player.wheatFields += 1

Now I know this is wrong, but if someone can explain why I am wrong, but I would like to know why.

On line 3 and 4, they declare the variables wheatFields and wheatProduction. That means that I can use player.wheatFields and player.wheatProduction to call them. On line 11, it is saying to increase the wheatFields by one. This variable successfully changes and saves on the main menu? How come the wheatProduction variable doesn't change if it is equal to wheatFields * 10?

Is it because it's in the initializer and only runs once? If that is the case, how can I make it to where it updates every time I add a wheat field to my player?

I tried doing this, too, but it said that the variable wasn't defined.

class Player():
    def __init__(self):
        self.wheatFields = 1
    wheatProduction = wheatFields * 10

This tells me that wheatFields is not defined, but it is just in the line above it.

EDIT: Thank you, dm03514, but I am still having some trouble. What your're saying makes sense, and I don't understand why this isn't working.

class Player():
    def __init__(self):
        self.wheatFields = 1
        self.wheatProduction = self.wheatFields * 10
    def wheatProduction(self):
        return self.wheatFields * 10
player = Player()
def main(player):
    print('Wheat fields: ' +str(player.wheatFields))
    print('Production: ' + str(player.wheatProduction))
    print('What do you want to do?\n1) Add wheat field')
    if input() == '1':
         player.wheatFields += 1
while 1:
    main(player)

This still causes wheat fields to go up, but when I call player.wheatProduction, it is staying the same for some reason.

Upvotes: 0

Views: 48

Answers (1)

dm03514
dm03514

Reputation: 55972

it doesn't change because it is only assigned 1 time when your class is initialized

There are a number of ways you can address it. If wheatproduction should always be based on wheatfields multiple you could turn it into a property so it is calculated every time you access it:

class Player():
   @property
   def wheatProduction(self):
      return self.wheatFields * 10

Upvotes: 2

Related Questions