The Python language contains the OO concept of a class. Rather strangely, it only really does half the job in that it doesn’t provide a way to properly encapsulate your class’ members.
Take this Java class, for example:
class Steve
{
private String name;
public String getName()
{
return name;
}
public void setName( final String n )
{
name = n;
}
}
This class is properly encapsulated. The getter and setter control the values that can be placed into, and read from, the name property.
You can’t do that with Python, you can create a similar looking class, like so:
class Steve:
name = "";
def getName(self):
return self.name;
def setName( self, n )
self.name = n;
But there is no way to make the name variable private – it is always public. You can define a variable with a leading double-underscore, like so:
class Steve:
__name = "";
def getName(self):
return self.__name;
def setName( self, n ):
self.__name = n;
This stops consumers from using Steve().name directly but __name is still not private – it is merely decorated differently. But it can still be obtained directly by using Steve()._Steve__name instead.
I’m not sure if the intention is to update this in a future version of Python – Python3000 breaks backwards compatibility so this is something that could go in. I hope it does get fixed.
Sign up for our daily email newsletter:
You must log in to post a comment.