Python NameError:未定义名称functionName
我的启动文件Python NameError:未定义名称functionName,python,python-3.x,Python,Python 3.x,我的启动文件 from UserInfo import UserInfo user = UserInfo() print(user.username) UserInfo.py文件 from fileinput import filename class UserInfo(object): """description of class""" username = ""; password = ""; def readConfig(fileName):
from UserInfo import UserInfo
user = UserInfo()
print(user.username)
UserInfo.py文件
from fileinput import filename
class UserInfo(object):
"""description of class"""
username = "";
password = "";
def readConfig(fileName):
config_file = open(filename,"r")
username = config_file.readline()
password = config_file.readline()
def __init__(self):
readConfig("config.txt")
异常:name错误:未定义名称“readConfig”
为什么readConfig函数在同一类中不可访问 您需要访问该类的实例。请尝试以下代码段:
def __init__(self):
self.readConfig("config.txt")
您的实现中缺少一些内容:
class UserInfo(object):
"""description of class"""
def __init__(self):
self.username = ""
self.password = ""
self.readConfig("config.txt")
def readConfig(self, fileName):
config_file = open(filename,"r")
self.username = config_file.readline()
self.password = config_file.readline()
第一个是您应该在
\uuuu init\uuu
方法中限定self.readConfig
。此外,在所有实例方法中,第一个参数必须是self
本身。是的,没有名为readConfig
的局部或全局变量。我建议阅读一些关于Python类的教程。很明显,您来自一种具有不同模式的语言。e、 例如,您没有显式地引用self
(这在python中是必需的),您正在创建无用的类级变量(即静态变量),您将立即在初始值设定项中隐藏这些变量。也许最能说明问题的是,您正在使用分号……为了在同一个类中引用该方法,您需要self.readConfig
,并且readConfig的参数应该是readConfig(self,fileName)
为什么要使用尾随分号?此外,“fileName”/“fileName”@ThomasWeller中似乎有一个输入错误。他可能是从Java语言的角度来理解的。看看他是如何在class语句中定义实例属性的。正如@juanpa.arrivillaga所提到的,变量应该属于实例而不是类。因此,它应该在\uuuu init\uuuu
中声明,并以self作为前缀。
除非将readConfig
作为一个实例方法,否则将无法工作,如另一个答案所示。