1

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?

1
  • 4
    Use @property. It will simplify this for you and remove all the hand-wringing. Commented Jul 6, 2011 at 15:22

3 Answers 3

10

In Python, you should prefer not to use getters and setters at all. Instead simply reference the count attribute directly, e.g. print instance.count or instance.count = 5

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

@property
def number(self):
     # do extra logic if necessary
    return self.count

Properties can also have setters - see: http://docs.python.org/library/functions.html#property

Python is not Java. =)

Extra bonus reading material:

Sign up to request clarification or add additional context in comments.

5 Comments

Oh, that's pretty cool. I can add setters if I really needed to later on with this.
Read through the article on tomayko and in the comments, there seems to be several reasons why it's not the best option, though I'm not sure if they are referring to the same thing.
@Keikoku: Care to cite specifics? All I've seen is either very subjective statements, originated from not reading the article properly, or dispelled in a later comment.
@delnan, it would be #6 and #17. Seems like some people don't like the idea of making it look like you're directly accessing attributes?
@Keikoku: Well, #6 is invalid IMHO since a change in a getter/setter method can just as well start raising exceptions etc. Alternatively (the last sentences seem to say so), the poster isn't opposing properties in particular but also getter/setters and everything else that. Equally invalid IMHO since he fails to name an alternative way to validate input that magically works with every client's code. As for #17, see the following comments.
2

Generally in python it's very bad style to use explicit getter/setter methods. Just do something like this:

In [1]: class Foo(object):
   ...:     def __init__(self):
   ...:         self.num = 1
   ...:         
   ...:         
In [2]: f = Foo()
In [3]: f.num
Out[3]: 1
In [4]: f.num = 2
In [5]: f.num
Out[5]: 2

If you really need logic, you can preserve this same API at a later date by using properties. Notice how the same interface is preserved below while still adding functionality.

In [8]: class Foo(object):
   ...:     def __init__(self):
   ...:         self._num = 1
   ...:     @property
   ...:     def num(self):
   ...:         return self._num
   ...:     @num.setter
   ...:     def num(self, num):
   ...:         if num < 0:
   ...:             raise ValueError("Your Foo would be too small!")
   ...:         self._num = num
   ...:         
   ...:         
In [10]: f = Foo()
In [11]: f.num
Out[11]: 1
In [12]: f.num = 2
In [13]: f.num
Out[13]: 2
In [14]: f.num = -1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/home/Daenyth/<ipython console> in <module>()

/home/Daenyth/<ipython console> in num(self, num)

ValueError: Your Foo would be too small!

Regarding "overloading" -- That term does not apply here. That is the term for changing the behavior of operators like +, ==, and so on, by changing the definition for those methods on your object. You can do some overloading in python via __cmp__, __add__, and so on.

4 Comments

That's "overriding". Overloading means two methods with the same name but different signatures. Which you can't really do in Python.
@FogleBird; Duh, you're right. I got it mixed up. You can do some overloading via __cmp__ and the like though.
@FogleBird: of course, you don't need to, since you can just use (*args, **kwargs), then behave differently based on what/how many parameters you're passed.
@FogleBird: Isn't that called "multiple dispatch"?
-1

I would leave it as two separate methods for the sake of code readabilty and maintainabilty.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.