Reputation: 659
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:
Any inputs? I am looking for a sample code!
Upvotes: 26
Views: 18374
Reputation: 2516
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.
Upvotes: 6
Reputation: 188024
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):
Upvotes: 3
Reputation: 547
As pointed by miku:
Objects can be serialized by picke module, but there is not an interface to be implemented, Python is not Java.
There is no private attribute in python, usually people use bar (the underscore) to mean private attributes, but they can be accessed from external world. Getters and setters are waste of time of both CPU and programmers.
Nothing to add to miku answer.
about properties: Real world example about how to use property feature in python?
good text: http://dirtsimple.org/2004/12/python-is-not-java.html
Upvotes: 1
Reputation:
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:
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).property
transparently.AttributeError
when a non-existent attribute is accessed).Upvotes: 34
Reputation: 34698
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.
Upvotes: 1