[Edu-sig] a question on java attributes vs. python
Leif Johnson
leif@ambient.2y.net
Tue, 29 Apr 2003 03:35:07 -0400
On Tue, 29 Apr 2003, ali wrote:
> is there a python counterpart for the declaration of class attributes in
> java like static, private, protected???
AFAIK there's no protected attribute. however, here's a class definition
with a static and a private variable :
class MyObject:
## this is shared among all class instances (static). it's accessed
## using self.instances
instances = 0
def __init__(self, attr):
self.instances += 1
## this is a private variable because it starts with '__'. within
## this class instance it's accessed using self.__myvar, but the
## interpreter does some name mangling so external objects can't
## have direct access, for example :
##
## >>> obj = MyObject('a')
## >>> print obj.__myvar # (error)
self.__myvar = attr
def get_myvar(self): return self.__myvar
def set_myvar(self, val): self.__myvar = val
def instance_info(self):
print self.instances, 'instances of MyObject have been created'
As I learn more Python I'm increasingly pleased with it. In this case, you
can think of all function definitions in a class as being static, just like
the static 'instances' variable above ; the function and data symbols are
simply shared among MyObject instances (although this is a bit more complex
with inheritance involved ; that's why class functions require the 'self'
parameter first, from what I understand it's how the static function code
is tied to a real class instance when called).
I think this is another good example of how Python and Scheme are really
not so different---functions are data are functions.
leif
--
Leif Morgan Johnson . http://ambient.2y.net/leif/
IAESTE trainee . http://www.iaeste.org/
Salomon Automation . http://www.salomon.at/