JavaBean equivalent in Python

  1. You can serialize most object via the pickle module;
  2. There are no such things as private attributes in Python (see also:
    • Does python have 'private' variables in classes?,
    • Actual implementation of private variables in python class);
  3. Classes that do not define a constructor will use a default (according to the method resolution order).

Example for constructor 'chain':

>>> class A(object):
...     def __init__(self):
...         print("A")
...     
... 
>>> class B(A): pass # has no explicit contructor
... 
>>> b = B()
A
>>> 

And - as @delnan wrote - you might want to read: http://dirtsimple.org/2004/12/python-is-not-java.html -- Java and Python have quite different cultures, it takes some time to dive into (and appreciate) both.

Also, after writing some code, it might be helpful to compare it to common idioms, as listed here (I certainly learned a lot this way):

  • http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/
  • http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
  • http://python3porting.com/improving.html

You don't, because Python is not Java. Most likely you should just write a less trivial class, construct a namedtuple, pass a dictionary, or something like that. But to answer the question:

  1. Neither serializable nor "implementing an interface" makes sense in Python (well, in some frameworks and advanced use cases it does, but not here). Serialization modules, such as pickle, work without implementing or inheriting anything special (you can customize the process in other ways, but you almost never need to).
  2. You don't write getters and setters. You just use public attributes. Should you later require a nontrivial getter/setter, you can turn it into a property transparently.
  3. There's no need for a dummy constructor, unless you want to create the attributes and set default values for them. But that's probably a bad idea (for a bean-ish class), as not assigning values to those attributes is most likely an error, and dubious even when it isn't. So just let Python catch those errors for you (it raises AttributeError when a non-existent attribute is accessed).

Well, I'd think that data classes would be similar to Java beans and that using them is actually a good idea, as it removes boiler plate.


Implements serializable.

Pick your favorite format, and write a function that will serialize it for you. JSON, Pickle, YAML, any work. Just decide!

Has getters and setters -> private properties

We don't do that here, those are attributes of bondage languages, we are all adults in this language.

dummy constructor

Again not something we really worry about as our constructors are a little bit smarter than other languages. So you can just define one __init__ and it can do all your initialization, if you must then write a factory or subclass it.