About classes and OOP in Python

Felipe Almeida Lessa felipe.lessa at gmail.com
Mon Apr 10 11:59:57 EDT 2006


Em Seg, 2006-04-10 às 07:19 -0700, fyhuang escreveu:
> class PythonClass:
>    private foo = "bar"
>    private var = 42
>    allow_readwrite( [ foo, var ] )

You are aware that foo and var would become class-variables, not
instance-variables, right?

But you can always do:

class PythonClass(object):
    def __init__(self):
        self.__foo = "bar"
    
    foo = property(lambda self: self.__foo)


And then:

>>> a = PythonClass()
>>> a.foo
'bar'
>>> a.foo = 'baz'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: can't set attribute


But you can also bypass this "security":

>>> a._PythonClass__foo = 'baz'
>>> a.foo
'baz'


But this was not a mistake, nobody mistakenly writes "_PythonClass__".

> Or allow_read to only allow read-only access. Also there might be a
> way to implement custom getters and setters for those times you want
> to modify input or something:
> 
> class PythonClass:
>    def get foo():
>        return "bar"
> 
>    def set var( value ):
>        var = value

There's a PEP somewhere that proposes things like (same example I gave
earlier):

class PythonClass(object):
    def __init__(self):
        self.__foo = "bar"    

    create property foo:
        def get(self):
            return self.__foo

-- 
Felipe.




More information about the Python-list mailing list