在Python类中访问嵌套函数
问题描述:
我是OOP的新手,我正在使用简单的概念。 一个例子:在Python类中访问嵌套函数
class test():
def a(self):
# how can I access here the function b()
b = self.a.b()
def b():
return 2
return b
test = test()
test.a()
在这里,我得到的错误信息:
AttributeError: 'function' object has no attribute 'b'
我也尝试了不同的版本有:
b = self.b()
然后我收到以下错误信息:
AttributeError: test instance has no attribute 'b'
非常感谢您的小时帮助
答
首先,在试图调用它之前声明函数。 然后按名称直接调用它。你并不需要使用self
或间接任何其他形式的,因为函数b()
是本地的方法a()
:
class test():
def a(self):
def b():
return 2
return b()
test = test()
test.a()
答
你需要在类中定义的函数B使用功能的,然后调用self.b( )。
我回滚了一个草率的编辑 –