Why less emphasis on private data?
Thomas Ploch
Thomas.Ploch at gmx.net
Sat Jan 6 19:41:05 EST 2007
time.swift at gmail.com schrieb:
> Coming from a C++ / C# background, the lack of emphasis on private data
> seems weird to me. I've often found wrapping private data useful to
> prevent bugs and enforce error checking..
> It appears to me (perhaps wrongly) that Python prefers to leave class
> data public. What is the logic behind that choice?
>
> Thanks any insight.
>
Python doesn't prefer public data in classes. It leaves the choice to
the programmer. You can define your own private instance variables (or
functions) by using a '__' prefix:
example:
class Foo:
def __init__(self, data):
self.__data = data
def get_data(self):
return self.__data
>>> f = Foo('bar')
>>> f.__data
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute '__data'
>>> f.get_data()
'bar'
More information about the Python-list
mailing list