Python 静态变量';实例中的范围是什么?
我对下面的Python静态变量片段感到困惑。执行时,我将访问实例变量。但如果我注释掉第#3行,则将访问静态变量。我想知道为什么实例方法的行为是这样的Python 静态变量';实例中的范围是什么?,python,python-3.x,Python,Python 3.x,我对下面的Python静态变量片段感到困惑。执行时,我将访问实例变量。但如果我注释掉第#3行,则将访问静态变量。我想知道为什么实例方法的行为是这样的 class Test: static_variable = "this is static variable" def __init__(self): self.static_variable= "this is some instance variable" # 3 def some_me
class Test:
static_variable = "this is static variable"
def __init__(self):
self.static_variable= "this is some instance variable" # 3
def some_method(self):
print(self.static_variable)
t = Test()
t.some_method()
如果您使用的是实例本身的
self
,则查找将发生在实例的范围内,并回退到类的范围内
在您的情况下,如果在
\uuuu init\uuuu
中分配变量,则将首先解析变量,如果不是,则将解析类属性。您可以使用self
或Test
访问类属性
print(self.static_variable)
print(Test.static_variable)
但是如果覆盖self.static_变量,则上面的两个调用将不会返回相同的值,并且
class Test:
static_variable = "this is static variable"
def __init__(self):
self.static_variable = "this is some instance variable" # 3
def some_method(self):
print(self.static_variable)
print(Test.static_variable)
# will give this
this is some instance variable
this is static variable
class属性
static\u变量
首先只是一个class属性,然后它作为class属性和实例属性存在在python中,当在类级别定义的静态变量成为类的属性时,一切都是对象。
当为一个类创建一个实例,并且我们在实例级别定义了与属性相同的名称时,我们会覆盖在类级别定义的属性。理想情况下,静态变量应该与Class.MethodName
一起使用。
试试这个:
class Test:
static_variable = "this is static variable"
def __init__(self):
self.static_variable= "this is some instance variable" # 3
def some_method(self):
print(self)
print(Test.static_variable)
print(self.static_variable)
t = Test()
t.some_method()
我不确定你期望得到什么样的答案。这就是语言的运作方式。这就像问为什么
def
定义了function@ViswanathPolaki . 它的类级变量名为static_variable我不确定这是否回答了这个问题,它感觉像是对它的重新表述。奥普知道这一切。他们问“为什么”,答案是“因为这是语言设计师们决定的”。我对范围感到困惑。谢谢@satvyk的澄清