PEP 8: on member variables vs. attributes
Dan Bishop
danb_83 at yahoo.com
Fri Jan 17 11:36:23 EST 2003
jbperez808 at yahoo.com (Jonathan P.) wrote in message news:<f57664b9.0301170041.46cc103e at posting.google.com>...
> From PEP 8:
>
> Designing for inheritance
>
> ... In general, never make data
> variables public unless you're implementing essentially a
> record. It's almost always preferrable to give a functional
> interface to your class instead (and some Python 2.2
> developments will make this much nicer)...
>
> But don't properties and data variables (as attributes) look
> the same anyway? So what's the diff between them, functionally
> speaking?
>>> class Foo(object):
... def __init__(self):
... self.__bar = ""
... def __getBar(self):
... return self.__bar
... def __setBar(self, value):
... if isinstance(value, str):
... self.__bar = value
... else:
... raise TypeError("bar must be a string")
... bar = property(__getBar, __setBar)
...
>>> baz = Foo()
>>> baz.bar = 4
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 10, in __setBar
TypeError: bar must be a string
If bar was just a data variable, you'd have no control over what got assigned to it.
More information about the Python-list
mailing list