Possible Duplicate:
Python: How to avoid explicit 'self'?
In python class if I need to reference the class member variable, I need to have a self. before it. This is anonying, can I not use that but reference the class member?
Thanks. Bin
Possible Duplicate:
Python: How to avoid explicit 'self'?
In python class if I need to reference the class member variable, I need to have a self. before it. This is anonying, can I not use that but reference the class member?
Thanks. Bin
To reference a class variables, you do not need explicit self
. You need it for referencing object (class instance) variables. To reference a class variable, you can simply use that class name, like this:
class C:
x = 1
def set(self, x):
C.x = x
print C.x
a = C()
a.set(2)
print a.x
print C.x
the first print would give you 1
, and others 2
.
Although that is probably not what you want/need. (Class variables are bound to a class, not object. That means they are shared between all instances of that class. Btw, using self.x
in the example above would mask class variable.)
I don't know of a way to access object properties as if they're globals without unpacking it explicitly or something.
If you don't like typing self, you can name it whatever you want, a one letter name for instance.
Writing self
explicitly is actually helpful. This encourages readability - one of Python's strengths. I personally consider it very useful.
A similar argument in C++ is that when you use using namespace std
, just to save repetitive prefixing of the std
namespace. Though this may save time, it should not be done.
So get used to writing self
. And seriously, how long does it take!
Python makes the reference to self explicit for a reason. The primary goal of the Python project is readability and simplicity. The "one correct way to do it" is to have a self argument and an explicit reference.
Do not question the benevolent one ...