3 ms·
Ask HN: Python: Procedural vs. Object-Oriented – what factors matter?
Having never worked as a programmer in my day job, I'm wondering when to write Python from an object-oriented paradigm vs. just procedural.
Case in point: https://github.com/dhruvkar/stic
I wrote a script to generate my static site. It's all functions, no classes. Looking at other, similar sized, site generator scripts, almost all have classes (e.g. [0]).
What factors matter when trying to decide which is right for the situation?
[0]: https://github.com/cbednarski/icecake
- new_hackers 10y agoBy 'Object-Oriented', I'm assuming you mean with classes? Since most (if not all?) variable instances in Python are object, then you will always be at some level working with 'Object-Oriented' code. However, you don't necessarily have to write in an 'object-oriented' style. Some of the typical arguments for classes are: * Inheritance * Polymorphism * Encapsulation of state with methods * Information hiding * Namespace With python you can't have information hiding easily (no "private" members). Also with python, since it uses duck-typing, you don't necessarily need classes to have polymorphic-like behavior. Python doesn't have a this variable, like C++, and all class methods require the beginning variable to be an instance of the object. So you could implement the same functions as simply a set of module functions that expect their first argument to have certain attributes. You do have inheritance, which when designing a "framework" can result in less code for your end users. However, you can do similar things with function decorators, and composition. Classes do provide a way to have a namespace, but so do modules, and functions. So at the end of the day, you don't really need classes (AFAIK), but if you like that style, it is available to you. TIMTOWTDI! A compelling reason to write code with classes is if you are integrating with another project that also uses this style.
- dhruvkar 10y agoThanks for this, clarifies a bunch for me. I haven't hit any of the compelling reasons, so going to stick with functions for now.