How to get/set class attributes in Python
tiissa
tiissa at nonfree.fr
Sun Jun 12 06:20:29 EDT 2005
Kalle Anke wrote:
> 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).
You can 'hide' you getsetters using a property attribute[1]:
>>> class person(object):
... def __init__(self):
... self.age = 0
... def set_age(self, age):
... print 'set %d' % age
... self.__age = age
... def get_age(self):
... print 'get'
... return self.__age
... age = property(get_age, set_age)
...
>>> joe = person()
set 0
>>> joe.age = 20
set 20
>>> print joe.age
get
20
>>>
[1]http://docs.python.org/lib/built-in-funcs.html
More information about the Python-list
mailing list