简体   繁体   English

如何在 Python 中嵌套方法

[英]How to nest methods in Python

This is a pretty basic question however, I struggled to find any answers online.这是一个非常基本的问题,但是我很难在网上找到任何答案。

I know that we can nest functions, however I wanted to see if we could do the same with methods in classes我知道我们可以嵌套函数,但是我想看看我们是否可以对类中的方法做同样的事情

Consider the example below:考虑下面的例子:

class name:
     def name(self):
            def name2(self):
                print("Hello world!")
             return self.name2()
    
 m = name()
 m.name()

Whenever I run the following code I get this error:每当我运行以下代码时,我都会收到此错误:

AttributeError: 'name' object has no attribute 'name2'

I would highly appreciate it if someone could help me find a solution.如果有人可以帮助我找到解决方案,我将不胜感激。

Your code makes no sense.你的代码没有意义。 name2 is just a local variable of the name method, and a regular function. name2只是name方法的一个局部变量,一个常规的 function。

class name:
     def name(self):
         def name2():
             print("Hello world!")
         return name2()
    
 m = name()
 m.name()

there, that works.在那里,那行得通。

Python methods are function attributes of class objects , they're not special or especially magical, but they certainly can't be defined as locals. Python 方法是class 对象的 function 属性,它们并不特殊或特别神奇,但它们当然不能定义为本地。

I have no idea what you're trying to achieve or what your mental model of the entire thing is, but I'm not sure either makes any sense.我不知道您要达到什么目的,也不知道您的心理 model 是什么,但我不确定两者是否有意义。

I think you're misunderstanding the way python classes work.我认为您误解了 python 类的工作方式。 If you've defined a standalone function inside a method, the function doesn't automatically become a member of a class.如果您在方法中定义了独立的 function,则 function 不会自动成为 class 的成员。

Rather you've defined a function just like any other function with the addition of a scope .相反,您已经定义了 function ,就像任何其他 function 一样,添加了scope The scope limits the visibility of the function within the method name() . scope 限制了方法name()中 function 的可见性。

I think this sums of your query and more.我认为是您查询的总和等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM