为什么 python 闭包在这种情况下不起作用?

问题描述

class Example:
    text = "Hello World"

    def function():
        print(text)

Example.function()  

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

为什么 printText() 不记得类属性 text
和python解释代码的顺序有关系吗?

解决方法

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

    class Example:
    text = "Hello World"

    def function(self):
        print(self.text)

如果你想保持静态使用:

def function():
    print(Example.text)


class Example:
    text = "Hello World"
,

使用 @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,将在该类的每个对象中更改。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...