【问题标题】:Why doesn't python closure work in this scenario? [duplicate]为什么 python 闭包在这种情况下不起作用? [复制]
【发布时间】:2021-06-03 01:34:22
【问题描述】:
class Example:
    text = "Hello World"

    def function():
        print(text)

Example.function()  

Example.printText() 抛出此错误NameError: name 'text' is not defined

为什么printText() 不记得类属性text
是不是跟命令python解释代码有关系?

【问题讨论】:

    标签: python closures python-class class-attributes program-flow


    【解决方案1】:

    函数是静态的 您需要使用 self 来访问对象属性 像这样:

        class Example:
        text = "Hello World"
    
        def function(self):
            print(self.text)
    

    如果你想保持静态使用:

    def function():
        print(Example.text)
    
    
    class Example:
        text = "Hello World"
    

    【讨论】:

    • "如果我想保持静态?我不明白"@eldad kdoshim
    【解决方案2】:

    使用@staticmethod 装饰器将函数设为静态。

    class Example:
        text = "Hello World"
        
        @staticmethod
        def function():
            # print(self.text) # raises error
            # because self is not defined
            # when using staticmethod
            
            # so you need to specify
            # the class name
            print(Example.text)
    
            
    # now its working
    >>> Example.function()  
    

    出来

    Hello World
    

    额外信息:

    • 变量text 将可用于使用此类创建的every object,如果您更改text,将在该类的每个对象中更改。

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2010-12-29
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多