[英]Programatically importing a file and creating an instance of a class in Python
[英]Attributes of a class instance not importing from a separate file
所以我正在開發一個基於 Python 的基於文本的游戲,我遇到了一個問題。 當我在另一個文件中使用主文件中的播放器 class 實例時,它不會保存屬性,例如名稱。 這是相關的代碼。
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 = ""
....
人.py:
import main
print(main.player.name) #prints an empty string
如果有任何澄清問題,請隨時提出; 這是我在這里的第一個問題。 謝謝!
為了解決一些問題,pickName 在 main.py 中被調用,因此它確實在 main.py 中運行並更改名稱,但不在它之外。
我解決了我的問題。 基本上,我將 class 的實例移動到定義 class 的文件中,然后導入該實例。 現在,它出於某種原因起作用。 如果有人知道為什么,請發表評論,但現在它有效,所以我不會抱怨。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.