Traceback:in in greet NameError:

时间:2014-10-29 18:19:27

标签: python variables global

有人可以帮我解决这个问题吗? 我收到这条消息:

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)

2 个答案:

答案 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)
#                                                  ^^^^^