有人可以帮我解决这个问题吗? 我收到这条消息:
Traceback: in in greet NameError: global name 'name' is not defined
由此:
class Person:
def __init__(self, name):
self.name = name
def greet(self, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
答案 0 :(得分:3)
name
超出了greet函数的范围。您需要使用self.name
代替。 e.g。
class Person:
def __init__(self, name):
self.name = name
def greet(self, other_name):
self.other_name = other_name
return "Hi {0}, my name is {1}".format(other_name, self.name)
您可以验证它是否有效
>>> mitch = Person('mitch')
>>> mitch.greet('mitchell') # prints 'Hi mitchell, my name is mitch'
>>> mitch.name # prints 'mitch'
>>> mitch.other_name # prints 'mitchell'
答案 1 :(得分:0)
name
是类Person
的实例属性。这意味着,您需要在其前面添加self.
来访问其值:
return "Hi {0}, my name is {1}".format(other_name, self.name)
# ^^^^^