2015-12-12 234 views
0

说我有类Test定义为这样:访问静态类变量

class Test 
    test_var = 2 
    def test_func(): 
     print(test_var) 

我可以找出test_var是好的,像这样:

>>> Test.test_var 
2 

...但调用Test.test_func()不起作用。

>>> Test.test_func() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 4, in test 
NameError: name 'test_var' is not defined 

如果我改变Test.test_func()像这样(注意,这是伪代码):

redef test_func(): 
    print(Test.test_var) 

它工作正常:

>>> Test.test_func() 
2 

...这是有道理的。但我怎样才能使第一个例子工作,切记,我想test_func是一个实例方法

请注意,上面发布的代码是示例代码,因此应该忽略拼写错误。

+0

您应该发布一个工作示例,以便让拼写错误发挥作用。你有这个“redef”的东西......但是它会更有助于展示你实际做了什么。 – tdelaney

+0

你的基本问题是'test_func'不是一个类方法或实例方法,所以它不知道类名称空间。 – tdelaney

+0

@tdelaney我刚刚重写了这个类,改变了这个函数。不是我怎么说它是伪代码。 – Quelklef

回答

1

您可以随时访问类级别通过实例的属性,即self,只要你还没有具有相同名称的实例属性遮蔽他们。所以:

def test_func(self): 
    print(self.test_var) 
0

您需要将自己(几乎总是您想要的)传递给类方法,或者在不需要自己的情况下添加@classmethod或@staticmethod装饰器。然后创建该类的一个实例并调用test_func方法。

Examples: 
# test_var is an class variable and test_func has a classmethod decorator 
>>> class Test: 
...  test_var = 2 
...  @classmethod 
...  def test_func(cls): 
...   print(cls.test_var) 
... 
>>> t = Test() 
>>> t.test_func() 
2 


# test_var is an class variable and test_func has a staticmethod decorator 
>>> class Test: 
...  test_var = 2 
...  @staticmethod 
...  def test_func(): 
...   print(Test.test_var) 
... 
>>> t = Test() 
>>> t.test_func() 
2 

# test_var is an instance variable here 
>>> class Test: 
...  self.test_var = 2 
...  def test_func(self): 
...   print(self.test_var) 
... 
>>> t = Test() 
>>> t.test_func() 
2 
+0

这不是问题,我上面发布的代码只是一个例子。好的眼睛,但。 – Quelklef

0

在你的榜样,test_func仅仅是一个函数,虽然其在类命名空间中定义,函数本身并不知道关于类的命名空间。你想要一个常规的实例方法或一个类方法。

class Test: 

    test_var = 2 

    def instance_test(self): 
     # instance methods will look in self first and class namespace second 
     print(self.test_var) 

    @classmethod 
    def class_test(cls): 
     # class methods take the class itself as first argument 
     print(cls.test_var) 

t = Test() 
t.instance_test() 
Test.class_test()