【问题标题】:Is it possible to have a function within a method in Python?是否可以在 Python 的方法中包含函数?
【发布时间】:2012-10-10 17:17:18
【问题描述】:

如果是这样,你会怎么做。

def 方法名(self, blah, blah) ^如何在其中放置一个函数。

【问题讨论】:

    标签: python function methods functional-programming


    【解决方案1】:

    是的,你只需在里面贴上def。你甚至可以在函数和方法中嵌套整个类:

    class Foo(object):
        def method(self, bar):
            def inner(magic):
                class Madness(object):
                    def __init__(inself, foo): inself.foo = foo
                return Madness(magic)
            return inner(bar)
    

    【讨论】:

    • 这对我不起作用。执行此操作时出现“赋值前引用的局部变量‘方法’”错误。
    • 最好将内部类中的 self 称为其他东西,例如这个或我,所以它不会与外部类的自我冲突。
    • @thebjorn:好电话。 @RahulSharma:为我工作(试试Foo().method(3))
    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2018-01-31
    • 2010-10-13
    • 2015-09-03
    • 1970-01-01
    相关资源
    最近更新 更多