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.
The function test
is only available in the local scope of first_method
. If you want to access it in other functions you will have to retain a reference to it somewhere. Something like the following will work:
>>> 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
Notice that there are a few changes to the question in the code. For example, the function test
takes no arguments. Also note that first_method
must be called before second_method
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.