
Ask HN: Python: Procedural vs. Object-Oriented – what factors matter? - dhruvkar
Having never worked as a programmer in my day job, I&#x27;m wondering when to write Python from an object-oriented paradigm vs. just procedural.<p>Case in point: https:&#x2F;&#x2F;github.com&#x2F;dhruvkar&#x2F;stic<p>I wrote a script to generate my static site. It&#x27;s all functions, no classes. Looking at other, similar sized, site generator scripts, almost all have classes (e.g. [0]).<p>What factors matter when trying to decide which is right for the situation?<p>[0]: https:&#x2F;&#x2F;github.com&#x2F;cbednarski&#x2F;icecake
======
new_hackers
By '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
Thanks for this, clarifies a bunch for me.

I haven't hit any of the compelling reasons, so going to stick with functions
for now.

