To access a class variable from an instance method, use class.variable name
.
python
In [1]: class A(object):
...: TEST = "test"
...: def test(self):
...: print(A.TEST)
...:
In [2]: a = A()
In [3]: a.test()
test
In fact, it is possible to access class variables via self (first argument of instance method)
.
python
In [4]: class A(object):
TEST = "test"
def test(self):
#It can also be accessed via self.
print(self.TEST)
...:
In [5]: a = A()
In [6]: a.test()
test
When accessing with self
, there is no problem if the class variable is immutable (read only). (Note: Python does not have a function equivalent to final in Java, so it is a gentleman's agreement to handle it without rewriting it)
However, if you want to make the class variable variable, it is possible that "I intended to rewrite the class variable but defined the instance variable with the same name" if I was not careful.
python
# A.A instead of TEST.I have assigned it to TEST.
In [7]: a.TEST = "instancetest"
#Class variables(A.TEST)Not an instance variable(a.TEST)Is referenced.
In [8]: a.test()
instancetest
I feel that class.variable name
is good in terms of surely accessing class variables, but it is vulnerable to changing class names.
Is it correct to rely on refactoring tools?
Recommended Posts