Reputation: 24788
I have this:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
print i # self.i will work just fine
return 'hello world'
When I do:
>>> x = MyClass()
>>>
>>> x.f()
I get an error, as expected.
My question is:
Why do I get the error?
Why is there no namespace between the namespace of the function(or method) definition and the global namespace of the module containing the class?
Is there any other way to reference i inside f in this case other than using self?
Upvotes: 2
Views: 2906
Reputation: 9
Why do I get the error?
Answer: This is because the variable i & the symbol/level f which points to a function/method code are in MyClass namespace where as the value/callable code/body of the function f lies in global namespace.
Why is there no namespace between the namespace of the function(or method) definition and the global namespace of the module containing the class?
Answer: Not sure why the python designer decided to put function name/symbol in the class but its body in global namespace.
Is there any other way to reference i inside f in this case other than using self?
Answer: I don't think so, but even if it is then it might not be easier logic/code
Upvotes: 0
Reputation: 10028
print i
is trying to print a global (for the module) variable i
. If you want to use the member of the class you should write self.i
.self
is the only usable way.Upvotes: 3