Python类定义

时间:2015-03-04 20:11:41

标签: python

这里有什么问题:

 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)

你可能意味着:

return "Hi {0}, my name is {1}".format(other_name, self.name)

您错过了self.变量之前的name

答案 1 :(得分:3)

需要在self参数上引用实例上的属性:

def greet(self, other_name):
    return "Hi {0}, my name is {1}".format(other_name, self.name)