2017-09-29 104 views
-1

我是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' 

非常感谢您的小时帮助

回答

2

首先,在试图调用它之前声明函数。 然后按名称直接调用它。你并不需要使用self或间接任何其他形式的,因为函数b()是本地的方法a()

class test(): 
    def a(self): 
     def b(): 
      return 2 

     return b() 

test = test() 
test.a() 
+0

我回滚了一个草率的编辑 –

0

你需要在类中定义的函数B使用功能的,然后调用self.b( )。