NameError:未定义name functionName

时间:2018-01-30 19:13:22

标签: 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):
        config_file = open(filename,"r")
        username = config_file.readline()
        password = config_file.readline()

    def __init__(self):
        readConfig("config.txt")

例外:NameError: name 'readConfig' is not defined

为什么在同一个类中无法访问readConfig函数?

2 个答案:

答案 0 :(得分:2)

您的实施中缺少一些内容:

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()

首先,您应该在self.readConfig方法中限定__init__。此外,在所有实例方法中,第一个参数必须是self本身。

答案 1 :(得分:1)

您需要访问该类的实例。请尝试以下代码段:

def __init__(self):
    self.readConfig("config.txt")