繁体   English   中英

为什么我不能从这个全局变量中调用 class?

[英]Why am I not able to call a class from this global variable?

所以我有一个主文件,然后我有我的所有功能的故事情节文件和一个 class。我有一个 class 设置用于我的用户输入,比如他们的名字。 然后我想将 class 作为全局变量放在我的主文件中。 当我尝试将主文件中的全局变量调用到故事情节文件中的 function 时,出现名称错误并且无法识别全局变量。 有人可以帮助解决我遇到的这个名称错误问题吗?

主文件.py

try:
    from storyline import *
except:
    print("The file storyline.py is did not load!")


go()
    
mycharacter = character()
 
intro()

故事情节.py

def go()
print("Welcome to the program, I hope you enjoy.")

class character:
    def __init__(self):
        self.setname()

    def setname(self):
        while True:
            print("Enter a username.")
            username = input('>:')
                 if username.istitle() == True:
                      self.name = username
                      print("Your username is{}.".format(self.name))
                      break
                else:
                    print("Please type a correct name.")
                    continue
def intro()
global mycharacter
print(f"Hello {mycharacter.name}. Welcome to the program.")

我认为您误解了课程及其工作方式,而且我认为您的某些缩进不正确。 您可能打算做的更多是沿着这些方向:

class character:
    def __init__(self, name):
        self.name = name
    
    def intro(self):
        print(f"Hello {self.name}. Welcome to the program.")

然后在你的其他文件中你可以这样做:

from storyline import *

mycharacter = character("bob")

mycharacter.intro() 

暂无
暂无

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

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