简体   繁体   中英

Attributes of a class instance not importing from a separate file

So I'm working on a text-based game in base Python, and I've encountered a problem. When I use my instance of the player class from the main file in another file, it doesn't save the attributes, for example the name. Here's the relevant code.

main.py :

from ply import Player

player = Player()

...

def pickName():
    global player
    print("And, what's your name?")
    player.name = input(">")
    print("Hello, %s!" % player.name) #this works

ply.py :

class Player:
    def __init__(self):
        self.name = ""

....

person.py:

import main

print(main.player.name) #prints an empty string

If there's any clarifying questions, feel free to ask; this is my first question here. Thanks!

To address some concerns, pickName is called within main.py, so it does run and change the name within main.py, but not outside of it.

I solved my problem. Basically, I moved the instance of the class to the file in which the class is defined, and just imported the instance. Now, it works for some reason. If anyone knows why, please comment, but for now it works so I'm not going to complain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM