2

I have some experience in R and I recently started to learn some python. I understand that there are some differences between methods and functions in python and how to call them on an object, but I do not see the benefit of using methods in general in python.

For me, using methods just adds another level of confusion, because in R, I could perfectly code everything just by using functions. But now, in python, the syntax of applying methods on an object is different, some methods alter the objects they are called upon and some methods only apply to some special classes of objects.

So, please excuse me respectfully asking: Did someone develop methods just to make everything a bit more complicated, or why did someone develop methods?

Andre Elrico
  • 10,956
  • 6
  • 50
  • 69
Kevin Südmersen
  • 883
  • 2
  • 14
  • 24
  • 3
    I do not think there is any special advantage, and will be based on what you want to do and how you like to program (OOP or functional). This is opinionated I think, and thus off topic, but if you ask specifically what are the advantages of one paradigm over the other, it may fit [softwareengineering.se], though make sure it is not a dupe. – kabanus Oct 25 '18 at 13:17

1 Answers1

4

I too think this is opinionated based on my understanding (and will be happy to remove my answer if deemed so), but I do believe they each have their places. Judging solely by the merits of their differences, methods don't exist outside of their class so they are specific to the class itself.

Consider this class Person:

Class Person():
    # ...
    def eat(self, food):
        return self.poop(food)

You can then invoke john.eat(burger) and it is perfectly readable code for any newcomer to maintain the new code base. But the function eat(john, burger) might be more of a brain fart as now you need to discern which object is performing the eat() function and which object is returning poop(). This might prompt you to peek into the eat() definition unnecessarily. Also, eat() doesn't make sense in the context of a Food class so it really doesn't need to be a function accessible to all objects. Thus, you can handle scoping in this aspect.

That said, more general purpose functions such as type() or id() might make more sense to exist outside of the classes as they can apply to a wide range of classes, and become good practice for DRY on definitions.

All in all, it greatly depends on how you structure your code. Thus, IMHO, opinionated per usage.

r.ook
  • 13,466
  • 2
  • 22
  • 39