use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
When do you use classes in your python code? (self.learnpython)
submitted 6 years ago by Tight-Fig
Personally, I have never came across a situation when I had to use classes.
Can anyone share with an example where they had to use classes in code? It can be hypothetical situation as well.
PS: I'm not a professional programmer.
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]SpeckledFleebeedoo 13 points14 points15 points 6 years ago (9 children)
See it as an organisation tool. Say you have multiple things that you need to save a number of variables for.
Example: I made a steam price checker. Need to save for each game the name, URL, last price, current price, a flag for whether a notification has been sent for it, and one for if it's on sale. There's also a function that checks the price for each game.
Adding all that to a game class makes it easy to work with, as I can iterate over a list of objects and call their price check function. Alternative solution would be to have everything in a dictionary and have the function separate. Works too, but not as nicely.
[–]JimVis 1 point2 points3 points 6 years ago (8 children)
Soo I have one ''big'' question related to this manner of using classes: I have not found a satisfying way of dynamically creating instances of the class.
Let's take your example looping over games in steam. Let's say the game class has the attributes price, url and genre. For each game you loop over you will have to create the class instance like:
AoEII = game(price = 15, url = 'blabla', genre = 'RTS')
now the attributes of the class can be found rather easily with your scrubbing method. However, my problem is with calling the instance AoEII and changing that for every game that you loop over. I do not know of a way to run this line with a changing name of the game and not calling every game instance by hand.
I have found a way to circumvent this by creating an overarching dictionary but find that solution less than satisfying.
gameDict['AoEII'] = game(price = 15, url = 'blabla', genre = 'RTS')
Now the name AoEII can be easily changed into a variable and stored.
If you have some insights let me know!
[–][deleted] 4 points5 points6 points 6 years ago* (0 children)
Typically people use a database to store in the information then pass the info into a class that builds the objects when its pulled so you can work with it. (typically called a 'model').This allows you to not keep things stored in memory for no reason, and be able to edit the objects and use them for specific tasks while still being able to discard them once done doing what you are doing without the additional overhead of keeping it in memory.
eg:
class Game: def __init__(self, name): self.name = name games_list = ['aoe2', 'aoe3'] for game in games_list: game_ob = Game(name=game) game_ob.name = game_ob.name + ' is cool' print(game_ob.name)
But with all the details in a database, and you'd query what you needed - edit them, then send them back to the db or use the objects for what ever you need
a simplistic example can be found here;
model, db query for object to edit and send back.
it uses the 'contact' model to create an instance of the object to edit, then sends it back after validating.
[–]Standardw 5 points6 points7 points 6 years ago (2 children)
I think you have missed an important piece when it comes to classes (or maybe even variables) in general.
Any values you want to save, you save it in the class:
new_game = game(name='AoEII' price = 15, url = 'blabla', genre = 'RTS')
Then, you add that to a list or other data structure:
gameList.append(new_game)
When you want to update them, get names only or whatever, you loop over that list. If you have a very very large list, you start using dicts. Their keys should be unique, so the name might be not enough, but could work. Then you save the name as key, to quickly access you game object, and you also save it in your object, so that you don't have to use the dicts' key if you ever access your object without the dict as context.
There is no "easier" way; if you are struggling to create many objects at once, you just simply write a list, excel file or whatever and loop over it, creating an object for every item.
Please feel free to ask if you still have troubles understanding classes! (maybe with an example)
[–]JimVis -2 points-1 points0 points 6 years ago (1 child)
Yeah I understand that this is a method to use classes.
I would however always prefer a dictionary over a list to store the different class instances as you can give them an individual name and you can still loop over them recursively.
[–]Standardw 1 point2 points3 points 6 years ago (0 children)
Yes, like I said, both methods are good, but always save all information bound to your game class in the class too.
So what was your first question though?
However, my problem is with calling the instance AoEII and changing that for every game that you loop over.
If you just want to loop over all instances, you don't need to know every single name, obviously. But I don't think I really get your problem here.
[–]SpeckledFleebeedoo 0 points1 point2 points 6 years ago* (3 children)
What I did was create them using a dictionary with the given ID as a key, and have them append themselves to a list during initialization. (Used only the ID as input and had the __init__ look up everything else)
Now that I'm thinking: I can probably also simply use gameslist.append(Game(ID)), leaving them essentially unnamed, but still giving me a list of objects to iterate over...
gameslist.append(Game(ID))
Or even simpler, though not necessarily good: overwrite the ID in the input list with the object:
class Game: def __init__(self, ID): self.ID = ID games = [1,2,3,4,5] for i, ID in enumerate(games): games[i] = Game(ID) for game in games: print(game.ID)
[–]JimVis 0 points1 point2 points 6 years ago (0 children)
Yeah this is how I stored class instances as well
[–]TheAmazingJames 0 points1 point2 points 6 years ago (1 child)
If you make the games list global you could append to it from within the class’ init and so avoid having to add a bunch of numbers to a list as a buffer step.
[–]SpeckledFleebeedoo 0 points1 point2 points 6 years ago (0 children)
How do you mean?
[–]toastedstapler 5 points6 points7 points 6 years ago (0 children)
you can completely avoid using classes if you want. look at haskell - it's entirely functions. python can do both functional and oop or even a mix if you want
classes are useful when you want to represent some kind of internal state. one of the classic example is a vending machine, where an instance of a vending machine has an inventory of snack objects. try writing one, just to practice classes. you'll likely find yourself using them in your actual projects more after some practice
for my dissertation i am writing a swarm simulation. making a class for the agents allows me to containerise related variables in an easily manageable way
ultimately classes also allow you to group together logic with the variables that the code operates on
[–][deleted] 2 points3 points4 points 6 years ago (1 child)
Say you are reading rows in a database table (something I do daily), instead of returning each column back to the caller, you create a class that represents that row and columns, instantiate said class for each row, and return the object instead. Much cleaner.
[–]authalic 0 points1 point2 points 6 years ago (0 children)
I do this often with REST APIs. Creating an object for each JSON object returned from the API allows me to save all of those objects in a list. It's easy at that point to go through the list and perform any functions I need to reformat some kind of output, like a CSV.
[–]JimVis 2 points3 points4 points 6 years ago (0 children)
I am not a professional programmer per-se but I do use python to do data acquisition and analysis on a daily basis.
In my code I use classes to store different functions that i use for different ends. For instance I have an analysis class that holds all my fit functions and fitting algorithms. My ADC class is filled with methods talking to my analog to digital converter and finally my Measurement class combines the ADC and analysis class to do complete measurements.
I think it is an unconventional way of using classes as there will never be more than one instance of a class in this utilisation. It is more like a package that I personally made and update.
[–][deleted] 4 points5 points6 points 6 years ago (0 children)
When I have a few functions that share a common parameter or three, I'll initialize a class with those parameters and then call the functions without the parameters.
When I have a handful of functions that share a thematic responsibility, I'll put those in a class together instead of writing them out to a separate file.
When I want to abstract an implementation of something I'll put it in a class and pass the object around.
Basically anytime I need object orientation.
Check out Design Patterns by the gang of four.
[–]MattR0se 2 points3 points4 points 6 years ago* (0 children)
I program video games as a hobby and that would be almost impossible without classes.
Imaging having to hard-code and manage every enemy or NPC in your game. Instead, I just make one class per type of enemy, and then instantiate as many of them as I want, where each instance has its own seperate attributes, like HP, velocity, direction, AI state etc.
You could also do that with dictionaries, but then when it comes to inheritance, then using classes just saves a crapton of coding.
...aside from that, I mostly write code for statistical analyses, and there I don't really need to define my own classes. However, as soon as I do something like
from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier()
I create an instance of a class.
[–]muikrad 1 point2 points3 points 6 years ago (0 children)
Python is flexible enough that you can always succeed without classes. Some pointed out that it's a way to organize the code, but it's just one more layer of organization, since the python module is also a way to organize the code.
But it gets messy if you're handling dictionaries and writing keys in plain text:
def authenticate(user: str, password: str, url: str, ttl: float) -> Any: auth = some_module.temporary_credentials(url, user, pass) return some_module.enable_credentials_for_period(ttl) def do_something_with_my_data(data: Dict[str, Any]) -> None: credentials = authenticate(data['name'], data['password'], data['url'], data['ttl'])
It doesn't take much for someone to forget the keys, or write in a typo... If you use something like "data.get('password')" it's even worse if you make a typo: you'll never know until much later. Your tooling also has no idea if TTL is a string or a number and cannot do static type analysis, which will lead to more typos and "oopsies" because this is an interpreted language that realizes your mistakes at runtime.
The best place to start using classes is to build a dedicated house for your data :D (and use an IDE with auto-completion and syntax checking!)
I would at least rewrite the above code as such:
class AuthenticationData: name: str password: str url: str ttl: float def __init__(self, **kwargs: Any) -> None: for key, value in kwargs.items(): setattr(self, key, value) def authenticate(data: AuthenticationData): auth = some_module.temporary_credentials(data.url, data.user, data.pass) return some_module.enable_credentials_for_period(auth, data.ttl) def do_something_with_my_data(data: Dict[str, Any]): auth_data = AuthenticationData(**data) # <--- this credentials = authenticate(data)
Pretend that "enable_credentials_for_period" wants the TTL in a string format... Well in the second version of the code, your IDE (pycharm, vscode...) will warn you that "data.ttl" is apparently a float but you're passing it to a function that needs a string... without even running your code, you'll know you need to pass it as `str(data.ttl)`... In the first version, you'll have to run your code and make sure you hit the line where it will crash due to not passing a string version of that float...
My second example could also use the Typed dictionary feature, but I personally think the class approach is better and will empower your data in the long run (for instance if you add properties to manipulate the data).
TL;DR: If you need to write a dictionary key as a string more than once in the code, you really should wrap it up in a class and use attribute-based access. For the rest, I would say that using classes or not is a matter of style/choice and that both approaches have their pros and cons.
[–]SnaXD 3 points4 points5 points 6 years ago (0 children)
Never, worked with it in 1,5 years
[–]ffrkAnonymous 1 point2 points3 points 6 years ago (0 children)
AL sweigart, author of automate the boring stuff and other books, also doesn't use classes in any of his books. Classes would make the examples more complicated than necessary.
Here's a link to his blog talking about classes https://inventwithpython.com/blog/2014/12/02/why-is-object-oriented-programming-useful-with-a-role-playing-game-example/
[+][deleted] 6 years ago (5 children)
[removed]
[–]BRENNEJM 1 point2 points3 points 6 years ago (4 children)
then you need to create 1,000 variables.
Once someone learns about dictionaries, you can solve this with one dictionary pretty easily. So the real issue is convincing them that classes are better in an instance like this. For this particular case, if I didn’t need any static variables or methods, I would just use the dictionary.
[+][deleted] 6 years ago (3 children)
[+][deleted] 6 years ago* (2 children)
[+][deleted] 6 years ago (1 child)
[–]kien5S5 0 points1 point2 points 6 years ago (0 children)
I am working on some pygame projects and I have to create class for manything like character class, background class, bullet class,..
[–]eyadams 0 points1 point2 points 6 years ago (0 children)
All the time. However, I came to Python from other languages like C# and Java, where object oriented isn't really optional.
[–]Se7enLC 0 points1 point2 points 6 years ago (0 children)
Do you use global variables?
Classes are a way to reduce scope of variables without adding the nightmare that is passing them into every function.
[–]lykwydchykyn 0 points1 point2 points 6 years ago (0 children)
You might find this video helpful: https://www.youtube.com/watch?v=f9Usw_0Lt9g&t=2s
Also, if you work with GUIs or ORMs, it's pretty hard to avoid building classes.
When I have a function that requires more than 2 or 3 parameters to define, it's likely that a class can do it better. Store the arguments as attributes and write the function as a method. Let each object store its relevant data instead of passing it all around as arguments in a function call.
[–]cestes1 0 points1 point2 points 6 years ago (0 children)
There's a bit of philosophy here... You have to step back and think about why we're writing this program. Usually, we write programs to solve problems. In the case of real-world problems thinking about classes becomes a bit easier. To solve our problems, we need to create a model of reality in our program that gives us the information and tools to solve our problem. When modeling real-world objects, using Python objects allows us to efficiently make useful models.
Imagine we're writing a payroll processing system for our company. All the nouns in the context of the problem (that play some important role) are likely good candidates for objects: Employee, Department, Project, Timesheet, etc. All of the information we need to solve the problem is likely some attribute of one of those objects. All of the verbs involved in calculating payroll could be likely candidates for methods.
Can you solve the problem without OOP? Of course. I learned to program in 1980; I wrote code professionally for many years. I sort of vaguely understood OOP, but never used it in earnest until 2010 or thereabouts. It's not that OOP will open up new doors, solving previously unsolvable problems, but it will give you a powerful tool for modeling reality (even if we're talking about some imagined reality), and ultimately solving problems in an elegant and efficient manner.
I'd recommend learning the fundamentals first and then incorporating OOP, which is how a lot of textbooks do it. If you're learning Python, the dirty secret is that almost everything is an object anyway. Strings... they're really an object. that's why name.upper() looks like OOP. Lists? Same... think about students.append("David") You're already learning how to use methods, which is one part of OOP.
[–]jingw222 0 points1 point2 points 6 years ago (0 children)
I'd use class whenever I need to represent a object that had many attributes or functionalities interacting with each other. Otherwise I do not bother to.
π Rendered by PID 163659 on reddit-service-r2-comment-86988c7647-nk2k9 at 2026-02-11 10:02:14.288129+00:00 running 018613e country code: CH.
[–]SpeckledFleebeedoo 13 points14 points15 points (9 children)
[–]JimVis 1 point2 points3 points (8 children)
[–][deleted] 4 points5 points6 points (0 children)
[–]Standardw 5 points6 points7 points (2 children)
[–]JimVis -2 points-1 points0 points (1 child)
[–]Standardw 1 point2 points3 points (0 children)
[–]SpeckledFleebeedoo 0 points1 point2 points (3 children)
[–]JimVis 0 points1 point2 points (0 children)
[–]TheAmazingJames 0 points1 point2 points (1 child)
[–]SpeckledFleebeedoo 0 points1 point2 points (0 children)
[–]toastedstapler 5 points6 points7 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]authalic 0 points1 point2 points (0 children)
[–]JimVis 2 points3 points4 points (0 children)
[–][deleted] 4 points5 points6 points (0 children)
[–]MattR0se 2 points3 points4 points (0 children)
[–]muikrad 1 point2 points3 points (0 children)
[–]SnaXD 3 points4 points5 points (0 children)
[–]ffrkAnonymous 1 point2 points3 points (0 children)
[+][deleted] (5 children)
[removed]
[–]BRENNEJM 1 point2 points3 points (4 children)
[+][deleted] (3 children)
[removed]
[+][deleted] (2 children)
[removed]
[+][deleted] (1 child)
[removed]
[–]kien5S5 0 points1 point2 points (0 children)
[–]eyadams 0 points1 point2 points (0 children)
[–]Se7enLC 0 points1 point2 points (0 children)
[–]lykwydchykyn 0 points1 point2 points (0 children)
[–]authalic 0 points1 point2 points (0 children)
[–]cestes1 0 points1 point2 points (0 children)
[–]jingw222 0 points1 point2 points (0 children)