instance vs class attributes
James Stroud
jstroud at mbi.ucla.edu
Tue Mar 29 20:37:50 EST 2005
Sarir said:
> Here are my questions:
>
> 1) What are the benefits of using a member variable without the 'self'
> qualifier? (I think this is because you can use _x without an
> instance of A().)
No such thing as a benefit here. self.a inside a method is the same as a
outside (see code below for what I mean).
> 2) Is there a preferred coding style (_x vs self.x)?
This is essentially a non sequitur.
> 3) Should private data be written as self._x instead of self.x?
This is a long standing debate. The usual answer is "we are all grownups
here", meaning that self.x is preferred. However, I personally like self._x
to let potential users of my code know that I intended it to be private.
The code I was talking about:
>>> class bob:
... a = 2
... def get_a(self):
... return self.a
... def set_a(self,an_a):
... self.a = an_a
...
>>> abob = bob()
>>> abob.get_a()
2
>>> abob.a
2
>>> abob.set_a(14)
>>> abob.a
14
>>> abob.get_a()
14
>>> class carol:
... self.a = 22
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in carol
NameError: name 'self' is not defined
James
--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com/
More information about the Python-list
mailing list