AB49K
AB49K

Reputation: 3425

Python class attribute seems to be resetting

I have 2 files here, one is a player.py

class playerinfo:
    def __init__(self):
        self.playername=None
        self.authtoken=None

And in the main file I've got

from player import *
p=playerinfo()
class MenuScreen(Screen):
    def __init__(self, **kwargs):
        super(MenuScreen, self).__init__(**kwargs)
    def login(self, Username, Passwd):
        if logindata != "11":
            p.playername=Username
            p.authtoken=logindata[0]


class PlayerScreen(Screen):
    def __init__(self, **kwargs):
        super(PlayerScreen, self).__init__(**kwargs)
    print(p.playername)

My problem is in the PlayerScreen class p.playername returns as None as set in playerinfo() If I print p.playername in the MenuScreen class it prints out the playername correctly.

Upvotes: 0

Views: 47

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125088

I see two problems:

  • the print statement is executed as part of the body of the PlayerScreen class. It is indented to the wrong level to be part of the __init__ method.

    You are mixing tabs and spaces in that part of the code making it possible that this is an accident. Don't mix tabs and spaces for indentation, you'll only get into more issues, configure your editor to expand tabs to spaces.

  • If the indentation is not correct in your question and print is part of the __init__ method, then you must be creating the PlayerScreen() instance before MenuScreen().login() is run, triggering the print before a playername has been set.

Upvotes: 1

Related Questions