Say I have class Test
defined as this:
class Test
test_var = 2
def test_func():
print(test_var)
I can find out what test_var
is fine like so:
>>> Test.test_var
2
...But calling Test.test_func()
does not work.
>>> 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
If I change Test.test_func()
like this (note that this is pseudo-code):
redef test_func():
print(Test.test_var)
It works fine:
>>> Test.test_func()
2
...and that makes sense. But how can I make the first example work, keeping in mind that I want test_func to be an instance method?
Note that the code posted above is example code, and so typos should be ignored.
3 Answers 3
You can always access class-level attributes via the instance, ie self
, as long as you have not shadowed them with an instance attribute of the same name. So:
def test_func(self):
print(self.test_var)
Comments
In your example, test_func
is just a function and although its defined in the class namespace, the function itself doesn't know about the class namespace. You want either a regular instance method or a class method.
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()
Comments
You need to either pass self (almost always what you want) to the class method or add a @classmethod or @staticmethod decorator if you don't need self. Then create an instance of the class and call the test_func method.
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
test_func
is not a class method or instance method so it doesn't know about the class namespace.test_func
not a class method?