class Test(object):
def __init__(self, name):
self.name = name
def new(self):
name = str(input('Name: '))
reg = Test(nombre)
return reg
person = new()
为什么这段代码会抛出“NameError:name'new'未定义”?
答案 0 :(得分:4)
我假设您正在尝试构建Test
类的新实例,并使用用户提供的名称加载它。
首先,您需要更正缩进。
其次,对于非类函数,您不需要self
参数。
class Test(object):
def __init__(self, name):
self.name = name
def new():
name = str(raw_input('Name: '))
return Test(name)
person = new()
请注意,更多Pythonic方式可能是将逻辑放入构造函数本身,就像这样。
class Test(object):
def __init__(self, name=None):
if name is None:
name = raw_input('Name: ')
self.name = name
person = Test()
答案 1 :(得分:1)
class Test(object):
def __init__(self, name):
self.name = name
@staticmethod
def new():
name = str(input('Name: '))
reg = Test(nombre)
return reg
person = Test.new() #ok since new is attached to a class namespace
person = new() # raises name error since new is part of Test, not the global namespace
或许也许
class Test(object):
def __init__(self, name):
self.name = name
def new():
name = str(input('Name: '))
reg = Test(nombre)
return reg
person = new() #ok since new is in the global namespace