When I need classes?

Michael Torrie torriem at gmail.com
Sun Jan 10 10:02:41 EST 2016


On 01/10/2016 12:29 AM, Arshpreet Singh wrote:
> Hello Friends, I am quite new to OOP(object oriented Programming), I
> did some projects with python which includes Data-Analysis, Flask Web
> Development and some simple scripts.
> 
> I have only one question which is bothering me most of the time, When
> I will get the need to use Classes in Python? Or in other way is
> there any real-life example where you can tell me this
> problem/solution is kind of impossible in Python without Classes?

I can't speak to Flask or any other web development.  But for simple
scripts, I'll start out with no classes.  Just functions as needed, and
some main logic.  I always use the idiom:

if __name__ == '__main__':
    # do main logic here

This way I can import functions defined in this script into another
script later if I want.

If I find I need to share state between functions, and if I find that I
might need to have multiple situations of shared state possibly at the
same time, then I will refactor the script into a class.  Despite the
apparent shame of using global variables, if I need to share state
between functions, but I cannot ever foresee a time when I'll need to
have multiple instances of that state, then I'll just use a module-level
global variable and continue to use normal functions, rather than define
a class.  In the parlance of OOP, this use case would be referred to as
a "singleton" and a python module (a script) is a form of singleton
already, even without using classes.

In the end my code often is a mix of classes and non-class -based code.



More information about the Python-list mailing list