In Python, when I'm defining a function inside a class, I can include self
as one of the arguments to access the member variables of that class, and I can also choose not include self
as the argument if I don't need to access its member variables. But then I discovered that if the function does not have self
as arguments, then it becomes invisible to other functions in that class. For example
class Test:
def __init__(self, val:int) -> None:
self.a = val
def f(a:int) -> int:
return a + 1
def g(self) -> int:
return f(self.a)
if __name__ == '__main__':
t = Test(2)
print(t.g())
The above codes will lead to the following error message:
Traceback (most recent call last):
File "/Users/louchenfei/Downloads/lc.py", line 11, in <module>
print(t.g())
File "/Users/louchenfei/Downloads/lc.py", line 7, in g
return f(self.a)
NameError: name 'f' is not defined
I wonder why that's the case and what are the rules for visibilities of functions defined in a class?