在dict变量中引用self的错误(python)

时间:2015-08-31 19:22:52

标签: python self

我对Python有点新意,无法想出这一点。我无法在我正在编写的某些代码中调试类似的错误。我在下面复制了它。

为什么当我在全局变量的dict中引用self.method()时,我得到一个名称错误?错误如下:

$ python -tt error_test.py
Traceback (most recent call last):
  File "error_test.py", line 1, in <module>
    class Test(object):
  File "error_test.py", line 4, in Test
    'key_one': self.method_one(),
NameError: name 'self' is not defined
class Test(object):

    some_dictionary = {
        'key_one': self.method_one(),
        'key_two': self.method_two(),
        'key_three': self.method_three()
    }

    def __init__(self): 
        pass

    def method_one(self):
        pass

    def method_two(self):
        pass

    def method_three(self):
        pass

2 个答案:

答案 0 :(得分:2)

我的猜测是你要这样做:

recv

答案 1 :(得分:1)

您必须在调用之前定义方法。你需要这样做:

class Test(object):    
    def __init__(self): 
        pass

    def method_one(self):
        pass

    def method_two(self):
        pass

    def method_three(self):
        pass



    some_dictionary = {
        'key_one': method_one,
        'key_two': method_two,
        'key_three': method_three
    }

此外,类级别没有self,仅在功能级别。如果需要使用self,则需要将字典定义移动到__init__或其他类方法中。

如果您希望some_dictionary成为Test的一员,则需要在__init__中定义,如下所示:

class Test(object):

    def method_one(self):
        print('Method 1')

    def method_two(self, x, y):
        print(x + y)

    def method_three(self, x):
        print(x * x)

    def __init__(self): 
        self.some_dictionary = {
        'key_one': self.method_one,
        'key_two': self.method_two,
        'key_three': self.method_three
    }

test = Test()
test.some_dictionary['key_one']()
test.some_dictionary['key_two'](1, 2)
test.some_dictionary['key_three'](6)

或者,如果您希望key_one, key_two, key_three成为这些函数调用的结果,那么这将起作用:

class Test(object):

    def method_one(self):
        return 'Method 1'

    def method_two(self, x, y):
        return x + y

    def method_three(self, x):
        return x * x

    def __init__(self): 
        self.some_dictionary = {
        'key_one': self.method_one(),
        'key_two': self.method_two(1, 2),
        'key_three': self.method_three(6)
    }

test = Test()
print(test.some_dictionary)