0
class Example:
    text = "Hello World"

    def function():
        print(text)

Example.function()  

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

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

4

2 回答 2

0

使用@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,将在该类的每个对象中更改。
于 2021-03-04T13:26:18.930 回答
0

函数是静态的,您需要使用 self 来访问对象属性,如下所示:

    class Example:
    text = "Hello World"

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

如果你想保持静态使用:

def function():
    print(Example.text)


class Example:
    text = "Hello World"
于 2021-03-04T12:01:02.403 回答