Look at this code:
class MyClass():
# Why does this give me \"NameError: name \'self\' is not defined\":
mySelf = self
# But this does not?
Python has an "explict is better than implicit" design philosophy.
Many languages have an implicit pointer or variable in the scope of a method that (e.g. this
in C++) that refers to the object through which the method was invoked. Python does not have this. Here, all bound methods will have an extra first argument that is the object through which the method was invoked. You can call it anything you want (self
is not a keyword like this
in C++). The name self
is convention rather than a syntactic rule.
Your method myFunction
defines the variable self
as a parameter so it works. There's no such variable at the class level so it's erroring out.
So much for the explanation. I'm not aware of a straightforward way for you to do what you want and I've never seen such requirement in Python. Can you detail why you want to do such a thing? Perhaps there's an assumption that you're making which can be handled in another way using Python.