Is it possible not to use the ego in the class?

Possible duplicate:
Python: how to avoid an explicit self?

In a python class, if I need to refer to a member variable of a class, I need to have self. before that. This is anonymity, can I use it, but refer to a member of the class?

Thanks. Bin

+4
source share
5 answers

No.

>>> import this ... Explicit is better than implicit. ... 
+5
source

To reference class variables , you do not need explicitly self . This is necessary for referencing objects ( class instance ). To refer to a class variable, you can simply use this class name, for example:

 class C: x = 1 def set(self, x): Cx = x print Cx a = C() a.set(2) print ax print Cx 

the first print will give you 1 and the other 2 . While this is possible, not what you need / need . (Class variables are bound to the class, not to the object. This means that they are shared between all instances of this class. Btw, using self.x in the above example, will mask the class variable.)

+2
source

I don’t know how to access the properties of an object, as if they were global, without unpacking it explicitly or something like that.

If you don’t like typing “I”, you can name it whatever you want, for example, one letter name.

+1
source

Writing self clearly helpful. This contributes to readability, one of Python’s strengths. I personally find this very useful.

A similar argument in C ++ is that when using using namespace std just to save the duplicate prefix of the std . Although this can save time, it should not be done.

So used to writing self . And seriously, how long will it take!

+1
source

Python makes an explicit reference explicitly. The main goal of the Python project is readability and simplicity. “One right way to do this” is to have your own argument and a clear link.

Do not ask benevolent ...

0
source

All Articles