K
Kalle Anke
I'm coming to Python from other programming languages. I like to
hide all attributes of a class and to only provide access to them
via methods. Some of these languages allows me to write something
similar to this
int age( )
{
return theAge
}
void age( x : int )
{
theAge = x
}
(I usually do more than this in the methods). I would like to do
something similar in Python, and I've come up with two ways to do
it: The first one uses the ability to use a variable number of
arguments ... not very nice. The other is better and uses
__setattr__ and __getattr__ in this way:
class SuperClass:
def __setattr__( self, attrname, value ):
if attrname == 'somevalue':
self.__dict__['something'] = value
else:
raise AttributeError, attrname
def __str__( self ):
return str(self.something)
class Child( SuperClass ):
def __setattr__( self, attrname, value ):
if attrname == 'funky':
self.__dict__['fun'] = value
else:
SuperClass.__setattr__( self, attrname, value )
def __str__( self ):
return SuperClass.__str__( self ) + ', ' + str(self.fun)
Is this the "Pythonic" way of doing it or should I do it in a different
way or do I have to use setX/getX (shudder)
hide all attributes of a class and to only provide access to them
via methods. Some of these languages allows me to write something
similar to this
int age( )
{
return theAge
}
void age( x : int )
{
theAge = x
}
(I usually do more than this in the methods). I would like to do
something similar in Python, and I've come up with two ways to do
it: The first one uses the ability to use a variable number of
arguments ... not very nice. The other is better and uses
__setattr__ and __getattr__ in this way:
class SuperClass:
def __setattr__( self, attrname, value ):
if attrname == 'somevalue':
self.__dict__['something'] = value
else:
raise AttributeError, attrname
def __str__( self ):
return str(self.something)
class Child( SuperClass ):
def __setattr__( self, attrname, value ):
if attrname == 'funky':
self.__dict__['fun'] = value
else:
SuperClass.__setattr__( self, attrname, value )
def __str__( self ):
return SuperClass.__str__( self ) + ', ' + str(self.fun)
Is this the "Pythonic" way of doing it or should I do it in a different
way or do I have to use setX/getX (shudder)