Reputation: 591
I used to be a java programmer and am currently changing to Python. In Java all functions are class methods, but I'm not sure what the situation is in Python. If I define a queue and want to know the size of the queue, what is the best design?
Define a variable __size, and define a method size()
Use @property at the method size to make __size readonly
Simply define variable self.size
My question is really focused on the coding style of Python, whether to make everything method or to use private variables. Is it preferable to use @property getters & setters for every variable?
Upvotes: 1
Views: 479
Reputation: 3409
I agree with Eli's link, in that usually getters and setters are extra cruft.
However, in this particular case, you should define a __len__()
method that will return the current size of your queue, allowing you to use the len(<obj>)
builtin to retrieve the length. Among other things, it will allow you to easily get a boolean value to determine if your queue is empty.
Upvotes: 3
Reputation: 273456
The Pythonic approach is just to have an attribute. If you later happen to need more functionality behind that attribute, you can always use the @property
decorator.
Read this for more details: http://eli.thegreenplace.net/2009/02/06/getters-and-setters-in-python/
Upvotes: 2