Use self.vars in class.method(parameters, self.vars)

Karim karim.liateni at free.fr
Fri Jul 22 13:26:11 EDT 2011



Be careful when using double underscore prefix the variable is "said" to 
be private but in fact you can modify it. It is a convention to say 
don't change it. And to discourage to use it python change its name
to '_<class name>__myvar' appending the prefix '_<class name>' to it.

See with your example:

karim at Requiem4Dream:~$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> a = foo()
 >>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', 
'__getattribute__', '__hash__', '__init__', '__module__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', '_foo__myvar', 'foo2']

In the instance namespace your attribute was transformed in '_foo__myvar'.
This is a veritable mess when you want to access from outside your class 
this attribute.
For maintenance when you inherited you have huge coupling NEVER DO THAT 
(advice):
In case you change the name of your class and reference this attribute 
in external class
you will end up with huge trouble to change the name in all referenced code.
With one '_' it says to others well this is my non public variable don't 
use it (this is a convention
because you can still modify it in python.

Cheers
Karim



On 07/22/2011 06:59 PM, caccolangrifata wrote:
> while i<  len:




More information about the Python-list mailing list