JavaBean equivalent in Python

javajavabeanspython

I am fairly new to using Python as a OOP. I am coming from a Java background. How would you write a javabean equivalent in python? Basically, I need a class that:

  1. Implements serializable.
  2. Has getters and setters -> private properties
  3. dummy constructor

Any inputs? I am looking for a sample code!

Best Answer

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).