class Example:
text = "Hello World"
def function():
print(text)
Example.function()
Example.printText()
抛出此错误NameError: name 'text' is not defined
为什么不printText()
记得类属性text
?
它与python解释代码的顺序有关吗?
class Example:
text = "Hello World"
def function():
print(text)
Example.function()
Example.printText()
抛出此错误NameError: name 'text' is not defined
为什么不printText()
记得类属性text
?
它与python解释代码的顺序有关吗?
使用@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
,将在该类的每个对象中更改。函数是静态的,您需要使用 self 来访问对象属性,如下所示:
class Example:
text = "Hello World"
def function(self):
print(self.text)
如果你想保持静态使用:
def function():
print(Example.text)
class Example:
text = "Hello World"