访问方法内的python类成员

时间:2013-07-22 05:34:36

标签: class python-2.7

这是我的代码

class Mine:
    def __init__(self):
        var = "Hello"
    def mfx(self):
        var += "a method is called"
        print var

    me = Mine()

当我致电me.mfx()时,它会出现以下错误

>>> me.mfx()

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    me.mfx()
  File "D:\More\Pythonnnn\text.py", line 5, in mfx
    var += "a method is called"
UnboundLocalError: local variable 'var' referenced before assignment
>>>

我只需要在课堂内使用var。 所以我不想要self.var。为什么会这样? 如何创建一个可以在类中随处使用的变量。 我正在使用Python2.7

3 个答案:

答案 0 :(得分:0)

您应该对var进行限定。 (self.var代替var

class Mine:
    def __init__(self):
        self.var = "Hello"
    def mfx(self):
        self.var += "a method is called"
        print self.var

me = Mine()
me.mfx()

答案 1 :(得分:0)

必须使用self,否则你创建的局部变量只能在创建它的方法中访问。

答案 2 :(得分:0)

您需要使用self来访问实例变量。使用新样式类并传入构造函数的参数

也更好
class Mine(object):
    def __init__(self, var):
        self.var = var

    def mfx(self):
        self.var += "a method is called"
        print self.var

me = Mine()
me.mfx()

如果您不想每次都传递“hello”,只需创建一个默认值

def __init__(self, var="hello"):
      self.var = var
相关问题