r/pythontips • u/Razhagal • Nov 26 '19
Why use classes?
Sorry if you are annoyed of this question, but I am having a hard time finding a reason to use classes or any real world examples of when I would use them over other methods. The thing most people say is just that if you have a lot of different variables, it simplifies the process and later changes by keeping everything in a class. But wouldn't it be just as easy and efficient to use functions and dictionaries? You can access, add, and change all sorts of variables in a dictionary and then use a function to easily access those variables. When would using classes be a better alternative to this, and what is a real world example?
Can anyone provide an example of code not using classes that is made better by using classes?
3
u/Razhagal Nov 27 '19
Thank you everyone for such detailed responses! I think I get it now. I just need to spend a bit more time working with classes so I feel more at ease with them and stop being so intimidated. Thank you!
8
u/484448444844 Nov 27 '19
I've been asking myself this lately and the answer is: Where it makes sense to (PS.there isn't actually a REAL answer).
The way I see it, if it's small script and you know what you need to do (I.E scrape this, do this to html file, extract this then create .csv) then it's faster and clearer to use functional programming
But if you're creating a large project that's more open-ended with multiple features (think something like MS Paint or a Web browser, AKA a fully fledged application) it's probably better to go with OOP
The easiest explanation I've found is on this site: https://www.educba.com/functional-programming-vs-oop/
Basically-
Use functional programming when there are few things (objects/data) and more operations
Use OOP when there is many things with few operations. When you know you will be reusing code/templates a lotWriting a script that logins into a mailbox and converts that email to a .txt files and then parses it and saves important info? Probably easiest to use procedural/functional programming (imo)
Writing a program to track check-in/check-out times of employees from a payroll system and display in a GUI or webpage for managers? Probably better to use OOP
2
u/Razhagal Nov 27 '19
Oooh okay, for some reason I felt like classes were being pushed as an all-the-time thing, but using them where it makes sense to makes.. well, sense!
3
u/B00fedurmom Nov 26 '19
Think about this way every built in library you use is a big class. So say you decide to make an app your app has two big performance functions. One is the backend management, the other handles the user interaction. They both need to interact, however; if you are just calling methods to modify and store data, which would be spread across multiple dictionaries/variables, things might get messy. It would be much simpler to have one big object that contains all that information based on whether you are working on the backend/user side. You can also checkout the Python discord and ask around there
3
u/OgorekDataSci Nov 26 '19
In one word, organization. I started my Pandas DataFrame scrolling project datascroller (fyi, current version is pretty rough) as a bunch of functions. It was simple but it was getting confused about where symbols were on the screen, how big the screen was, etc. I was honestly too confused (or not smart enough) to keep it all straight. So I created the classes ViewingArea and DFWinder in this version (much improved, about to be released). Things were still hard to figure out, but I could solve problems in pieces and then put the pieces together.
3
u/DBA_HAH Nov 27 '19 edited Nov 27 '19
I mean... almost everything you touch uses classes.
Let's take reddit. How would you handle users without a class? Retrieve the info from the database and push it into a dict? Now what if you want to delete the user? Create a separate function called `delete_user` that accepts a dict?
What if you want to enable validation on a created user (valid email, username not taken, etc)? Are you always going to do that on the database layer? Or are you going to have a separate function called `validate_user` that accepts a dict?
Etc, etc. You end up with a clusterfuck of functions that all accept any dict.
The best example of using classes probably comes from inheritance. Let's say we also want to include admins in reddit which are a subclass of users. Maybe admins are considered employees so they get extra fields such as mailing address, real name, telephone number, etc but also get to function as users on reddit. Without classes you would create a different dict structure with 90% of the code being duplicated whereas with classes, an Admin would inherit everything from dict and you would only add what's specific for Admins.
Now lets say you need to make a change so that any User can have a longer username or users can now have a friend's list. Without classes, you now need to change the code in two places (User and Admin dicts) whereas with classes we only have to do it once since we use inheritance. Now imagine if there were 12 different kinds of users. With classes you only ever have to change the code in one place.
The reason why we use classes is to organize the code. It's much easier to find out how a program creates, validates, deletes a user when it's all stored in a User class than trying to find out which functions to use, hoping the function names are clear, etc.
Beyond this, using OOP unlocks Design Patterns which have decades of research and real-world use behind them as proficient ways to design programs.
If you're just hacking around with scripts and the like then you probably don't need a class. But if you're designing an application that's going to have many recurring objects (users, cars, comments, Tweets, emails, line items, products, etc) then you realistically need classes.
TL;DR - Make your code DRY - don't repeat yourself. If you find yourself repeating yourself, you need to investigate why and often times there's an OOP principal or design pattern to fix it.
3
u/guillermohs9 Nov 27 '19
As other users stated, organization is a big reason.
It may seem like a vague or too simple explanation, but at some point you truly grasp the concept of OOP, and you naturally incorporate it to your designs. It may be the same point that you face a larger project.
I've always used hacky scripts with a functional programming style. I knew how OOP worked, but I hadn't felt the need to use it. At one point it came as some sort of epiphany and it felt so good to naturally come up with a static method or subclass an imported class to solve some particular problem.
2
u/joshfokis Nov 27 '19
Same boat for me. I was always confused by it even though I understood the concept of it. But it wasn't until I started a project that made more sense to write a class and not keep writing the same or similar code.
3
u/Dogeek Nov 27 '19
The truth is, you never have to use OOP, and ultimately, it depends on your goals.
If you want just a quick, one-time use, script, then you don't need OOP, more often than not, it'll make the problem more complex than it needs to be.
OOP is useful when you want to work on larger scale projects, stuff that you'll be maintaining and working on for months, years or even decades. In that scenario, you want to have clean, self-documenting code, that you can easily modify to add new features.
OOP just makes it easier to scale and maintain things. You can absolutely do the same with functions and dictionaries. The code will just be harder to read and understand, harder to maintain, and won't scale well. It's just more convenient to write a simple class to handle all of that.
Also, OOP is not just about classes, it's also about metaclasses, decorators, generators, iterators, inheritance and so on. A good programmer is lazy, and you'll want to avoid rewriting code as much as possible (or avoid circular imports for instance), and that's when OOP shines.
2
u/CBSmitty2010 Nov 26 '19
Organization and saving you from rewriting code.
Start doing a bigger project and classes will pay for themselves.
2
u/McPokeFace Nov 26 '19
Classes encapsulate the implementation so that it can changed without affecting the behavior of the methods being called. A Stack would be an example. There would be public methods such as push, pop, isEmpty.. The private implementation could initially start using an array and then be changed to a linked list later without impacting whatever objects are calling the public methods since the behavior does not change.
0
Nov 27 '19
[deleted]
2
u/Razhagal Nov 27 '19
Thanks for your detailed response and examples! This definitely helps put it in perspective. It's easier to see it with complex code like yours versus the simple code I've been tinkering with!
5
Nov 27 '19
[removed] — view removed comment
1
u/Razhagal Nov 27 '19
Thank you for a great example! That helps a lot and I think I am getting now when they are appropriate to use.
3
u/joshfokis Nov 27 '19
This is what I was trying to get at with my comment and you gave a great example.
20
u/joshfokis Nov 26 '19
Best way I have heard it described and pitched for using classes would be a DnD character creator. You have some of the same variables for each character.
Characters will have the followings similarities: Name Race Strength Dexterity Constitution
Amongst several others. The reason to do this is not to overwrite a variable that they would all need. What this does is creates an object for each character, and in each object the variables used will all have different values from each other.
So if you had 5 characters you would need 5 times the variables. Char_1_name Char_2_name etc.
But not only can this be used just for characters it could also be used in a similar way for monsters too that have also some of the same variables.
Functions do have their place, especially when writing small scripts.
Sorry if this has bad formatting, typing this on the phone is difficult enough. Also if this is a bad explanation or not thorough enough please jump in. I do hope this helps.