[Tutor] Creating a pojo in python
Dave Angel
davea at davea.name
Mon Feb 9 17:50:39 CET 2015
On 02/09/2015 02:20 AM, rakesh sharma wrote:
> How can one create a POJO in python.I mean a class like this
> class A { private a; private b; public getA() { return a; } public getB() { return b }}
> I tried creating class in python but the variables were accessible as public data members.
> Any help?
The other respondents so far (Danny, Alan, and Mark) are right on. But
there are times when you might want APPROXIMATELY what you call POJO in
Python.
Obviously you wouldn't want exactly that, since that class is totally
useless. Without any setters or constructor, those class members cannot
be initialized to any value. (I don't know if java has the equivalent
of C++ friends, or whether derived classes could change those private
values, so I may be wrong here)
So the real question is why DO you want the Python version of this.
If it's because your teacher is trying to make some point, and assigned
you to figure this out, then try using the @property decorator on the
get function. Naturally, the get function is called a, and the private
data is _a_hidden_attribute_that_you_dont_want_the_caller_to_use
The public interface of that class is then just the same as though the
class had a and b attributes, except that writing to those will give a
runtime error.
If it's because you have a bunch of code that you already transliterated
from java, and it uses this class you haven't written yet, then my
sympathies. I've been there, and the cure is to go back to all those
uses, and change each function call of the form:
obj.getA() to
obj.a
If all that code was transliterated by somebody else, and you're not
allowed to mess with it, then go back to the teacher example.
--
DaveA
More information about the Tutor
mailing list