简体   繁体   English

未从单独文件导入的 class 实例的属性

[英]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.所以我正在开发一个基于 Python 的基于文本的游戏,我遇到了一个问题。 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.当我在另一个文件中使用主文件中的播放器 class 实例时,它不会保存属性,例如名称。 Here's the relevant code.这是相关的代码。

main.py : 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 : ply.py

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

....

person.py:人.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.为了解决一些问题,pickName 在 main.py 中被调用,因此它确实在 main.py 中运行并更改名称,但不在它之外。

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.基本上,我将 class 的实例移动到定义 class 的文件中,然后导入该实例。 Now, it works for some reason.现在,它出于某种原因起作用。 If anyone knows why, please comment, but for now it works so I'm not going to complain.如果有人知道为什么,请发表评论,但现在它有效,所以我不会抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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