Is It Possible Not To Use "self" In A Class?
Solution 1:
No.
>>>import this...
Explicit is better than implicit.
...
Solution 2:
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:
classC:
x = 1defset(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.)
Solution 3:
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.
Solution 4:
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!
Solution 5:
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 ...
Post a Comment for "Is It Possible Not To Use "self" In A Class?"