问题描述
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
,将在该类的每个对象中更改。