I think the concept is called overloading.
Right now I’m writing a class that will provide getter and setter methods, and am stuck on a design issue.
Both methods are one-liners that simply set a value, or return a value.
def set_number(self, num): self.count = num def get_number(self): return self.count
Would it be better to save space and make the class “look” smaller by doing something that will basically combine the two methods into one and then just decide which line should be executed depending on whether the num argument is provided?
Or should I just stick to clarity and keep them separated? Some people feel that it’s a “waste of space” to keep all these one-liners on their own, while others disagree and prefer splitting them up.
Any reasons why I would choose one or the other?
In Python, you should prefer not to use getters and setters at all. Instead simply reference the
countattribute directly, e.g.print instance.countorinstance.count = 5The point of getters and setters in other languages is for encapsulation and for future-proofing in case you need to add logic to the getters or setters. In Python you can accomplish this by later using
property, which will not break your existing API.Properties can also have setters – see: http://docs.python.org/library/functions.html#property
Python is not Java. =)
Extra bonus reading material: