【问题标题】:Nested Function in a Class, Python类中的嵌套函数,Python
【发布时间】:2018-09-19 20:26:34
【问题描述】:

我正在尝试在类中使用嵌套函数。这是我的代码

class big():
        def __init__(self):
        self.mas = "hello"

    def update(self):

        def output(self):
            print(self.mas)

        self.output()

thing = big()

thing.update()

但是,当它运行时,我收到未定义输出的错误。如何在更新函数中运行输出函数?

【问题讨论】:

    标签: python-3.x function class nested


    【解决方案1】:

    只需将其称为output(),而不是self。您定义它的方式,它基本上是 update 方法中的局部变量,而不是类的属性。

    class big():
        def __init__(self):
            self.mas = "hello"
    
        def update(self):
            def output():
                print(self.mas)
    
            output()
    
    thing = big()
    
    thing.update()
    

    【讨论】:

    • 你可能不应该将self 作为参数传递给output,但如果你这样做了,你应该在调用中传递它。就目前而言,它引发了TypeError: output() missing 1 required positional argument: 'self'
    • @ReblochonMasque 我的错误,已修复
    猜你喜欢
    • 2010-12-08
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2021-09-02
    • 2012-02-05
    相关资源
    最近更新 更多