getFoo1() vs. class.foo1

Hans Nowak zephyr01 at alltel.net
Fri Jun 13 19:51:20 EDT 2003


Manuel wrote:
> Hi, I'm python beginner.
> My first class is very simple, like
> 
> class VerySimple:
>         foo1 = 1
>         foo2 = 2
>         foo3 = 3
> etc...
> 
> Any professional developers tell me that
> I must use get and set (to private variable)
> method instead.

They're wrong.  :-)  It's possible to define private attributes, kind of, but 
Python doesn't encourage it, and often you don't need it.  But that's a 
discussion for another time.

Besides that, this is how you usually add and initialize attributes:

class VerySimple:
     def __init__(self):
         self.foo1 = 1
         self.foo2 = 2
         self.foo3 = 3

These are instance attributes; attributes like

class VerySimple:
     foo1 = 1

are class attributes, which are shared by all instances of that class.

> class VerySimple:
>         __foo1 = 1
>         __foo2 = 2
>         __foo3 = 3
> 
>        def getFoo1(self):
>             return __foo1

By the way, this code won't work, because __foo1 isn't known inside the body of 
method getFoo1.  Ditto for the other methods.  To set a class attribute, use 
something like

   self.__class__.foo = 'bar'

HTH,







More information about the Python-list mailing list