1

I am trying to access inner method in python from another method but on doing this it is giving me "AttributeError: 'function' object has no attribute 'b'"

My Scenario is:

class Foo:
    def first_method(self):
        something
        def test(self):
           print 'Hi'

    def second_method(self):
       a = self.test()

The line a = self.test() is throwing an error.

4

1 回答 1

6

该功能test仅在本地范围内可用first_method。如果您想在其他功能中访问它,则必须在某处保留对它的引用。像下面这样的东西会起作用:

>>> class Foo:
...     def first_method(self):
...         def test():
...            print 'Hi'
...         self.test = test
...     def second_method(self):
...         self.test()
... 
>>> f = Foo()
>>> f.second_method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in second_method
AttributeError: Foo instance has no attribute 'test'
>>> f.first_method()
>>> f.second_method()
Hi

请注意,代码中的问题有一些更改。例如,该函数test不接受任何参数。还要注意first_method必须在调用之前second_method

于 2012-06-15T11:43:49.990 回答