NameError: name 'User' is not defined
NameError: name 'User' is not defined
当我在 Visual Studio 代码和 Jupiter 中键入它时,此代码不会 运行,并且我收到“NameError:名称 'User' 未定义”错误消息。然而,当我从作者的网站复制并粘贴完全相同的代码时,它 运行 非常完美。我已经阅读了我可以在网上和 Python 3.9 文档中找到的所有内容,但无法弄清楚原因。这是代码:
class 用户():
"""Represent a simple user profile."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
def describe_user(self):
"""Display a summary of the user's information."""
print(f"\n{self.first_name} {self.last_name}")
print(f" Username: {self.username}")
print(f" Email: {self.email}")
print(f" Location: {self.location}")
def greet_user(self):
"""Display a personalized greeting to the user."""
print(f"\nWelcome back, {self.username}!")
john = User('john', 'bassett', 'Jack', 'jack@me.com', 'L.A.')
john.describe_user()
john.greet_user
如果我不得不猜测那将是格式问题。空格(制表符和空格)在 Python 中是有意义的。 Whosebug post 此处的格式设置已关闭,因为“class User”行位于预格式化代码块之外,并且所有 class 的方法都在错误的级别缩进.你想要这样的东西:
class User():
def __init__(self):
return
def another_method(self):
return
john = User('john')
当我在 Visual Studio 代码和 Jupiter 中键入它时,此代码不会 运行,并且我收到“NameError:名称 'User' 未定义”错误消息。然而,当我从作者的网站复制并粘贴完全相同的代码时,它 运行 非常完美。我已经阅读了我可以在网上和 Python 3.9 文档中找到的所有内容,但无法弄清楚原因。这是代码:
class 用户():
"""Represent a simple user profile."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
def describe_user(self):
"""Display a summary of the user's information."""
print(f"\n{self.first_name} {self.last_name}")
print(f" Username: {self.username}")
print(f" Email: {self.email}")
print(f" Location: {self.location}")
def greet_user(self):
"""Display a personalized greeting to the user."""
print(f"\nWelcome back, {self.username}!")
john = User('john', 'bassett', 'Jack', 'jack@me.com', 'L.A.')
john.describe_user()
john.greet_user
如果我不得不猜测那将是格式问题。空格(制表符和空格)在 Python 中是有意义的。 Whosebug post 此处的格式设置已关闭,因为“class User”行位于预格式化代码块之外,并且所有 class 的方法都在错误的级别缩进.你想要这样的东西:
class User():
def __init__(self):
return
def another_method(self):
return
john = User('john')