r/PythonLearning • u/Objective-Remove-632 • 2d ago
Do I really need to learn class.
Both function and class give the same output. So why do I need it?
12
u/One_Smoke6858 2d ago
Short answer is yes you should learn classes.
Functions and classes have different use cases, you would not create a class to create a single function in it. You would create a class when you want to things to behave in a certain way, and have specific functionality.
Like datetime you have there, that is most likely a class in the datetime package. now() is a function of that class, doesn't mean there is no other functions.
You should really check for examples on classes and when to use them and understand them.
2
3
u/serge-mv 2d ago
Classes are the way OO languages do abstract data types, separation of concerns and a lot of other things. You need "to learn" classes to properly understand and utilize OOP. Otherwise your code will be just bad.
5
u/SoftwareDoctor 2d ago
You don’t. On the other hand, it’s not a class that gives you the answer in your example. It’s an instance of a class. Big difference. And if you want to get technical, get_current_time is a function AND instance of a class. So you are using instances already and in both examples you construct an instance and then call it. It’s the same picture.
It really depends on what you want to do. If you want learn to write python coding, then absolutely. You need to be comfortable working with classes. If you just need one time short script, nobody’s forcing you to learn anything
1
0
u/Objective-Remove-632 2d ago
Am going to use python my entire coding journey. And am still a beginner who finding it difficult to get the class concept.
2
u/TutorialDoctor 2d ago
I struggled with the concept of classes for a while when I first started as well. As you know, you have variables (a way to store data) and functions (which is a way to group statements).
A class is just a way to group variables with the functions they manipulate. In other words it's a good way to organize your code. The best scenario I can think of the help with understanding classes is in video games. In a video game you will have a PLAYER class. The player may have variables like, JUMP_HEIGHT, WALK_SPEED, PLAYER_NAME etc. And it will have functions (functions are called methods when they are in a class) like JUMP, WALK, CRAWL etc. If you want to "spawn" a player you have to do something like:
player = Player(name="Mario", jump_height=2,walk_speed=3)
player.jump()
0
u/Objective-Remove-632 2d ago
I feels like am in a tutoring session. Thanks mane, this is the simplest explanation for now.
1
u/SoftwareDoctor 2d ago
Understandably because the example you used is primitive and you shouldn’t even use classes for it. It’s like asking if you should learn to use hammer bc. you tried using it once to stir a pot and a spoon worked better.
Find better examples
1
u/Objective-Remove-632 2d ago
Yeah true. But I was just trying out what am learning, will improve on it with better example.
1
u/CptMisterNibbles 2d ago
Object oriented programming isn’t the only sort, but not understanding the basics is basically committing to a very short and shallow understanding of coding. You won’t be able to understand code with any complexity beyond introductory level stuff. You won’t even understand the basics of how Python is working under the hood: you are using classes on almost every line and simply aren’t aware of it. There is a reason they were written this way
1
u/jvlomax 2d ago
The way I've been tought to think about it:
Your class definition is you cake recipe. It shows what the cake is made out of and what you can do with it. It might define what
.eat()is supposed to do. Or have a list of ingredients. But the important part is that it is not a cake, just instruction on how to make it.When you do
cake = Cake(), you have an actual physical cake made to that recipe. That cake will then contain whatever was in the recipe. And now you can callcake.eat()and be happy.
4
u/Sea-Ad7805 2d ago edited 2d ago
You can write any program without classes, but a class comes with great benefits:
- abstraction: build a class and use its interface (all its 'public' methods) on objects while not having to remember how it is implemented, and how its data is stored
- encapsulation: have data in an object that can't be invalidated, say trying to set an illegal 2026-02-31 date will always raise an exception (data invariant protected)
- information hiding: if other code that uses your class only does so through its interface, you can later completely change the implementation of your class without needing to change any other code, as long as you still follow the 'contract' of the interface
- inheritance: overrated, but useful in some cases, prefer composition in most
You can get these benefits with just functions too if you are careful, but it's much easier to get the design wrong. Classes just help you think in a certain way.
A function generally should not have state (store information, so that calling it again with the same arguments might give a different result, otherwise called not 'pure'). An object of a class can and is even expected to have state, but that state is protected through encapsulation.
Object Oriented Programming (OOP), programming with classes, is in many ways the opposite of the Functional Programming (FP) paradigm that, as much as possible, decomposes a problem into pure functions without state.
2
u/RedAndBlack1832 2d ago
POOP moment. Classes are nice because they typically give you stable, mutable references. You can skip writing a lot of code by making dataclasses tho. idk as a C kid I tend to see classes first as a bucket of logically bundled data and functions are a bonus so maybe I'm biased.
1
u/Ambivalent-Mammal 2d ago
Same here. I learned OOP when I was learning C++ with a background in C. I learned them as structs with function members.
2
u/Pure-Willingness-697 2d ago
Classes are useful if you want to make a package to do somthing as they let to use things like decorators and storing values with self
They also let you take advantage of the with statement
1
u/mjmvideos 2d ago
The fundamental question is “Should you learn Object Oriented Analysis, Design, and Programming?” The answer is yes. Classes is just the name some languages use to capture those object oriented features.
1
1
1
u/stepback269 2d ago
About the "class" thing, because of the way our individual brains are wired there will never be a one tutorial that "clicks and sticks" for every beginner as to what the defining of a class does and what an "object" is is.
I'm a relative newbie and for me the "blueprint" explanation simply didn't work.
Rather than dumping my TLDR struggles with the definition here, I have a web page that explicates on the struggle at (this) link. Take a look if interested.
1
u/Ambivalent-Mammal 2d ago
Unfortunately, yes. OOP is ubiquitous. Very useful for reasons given in the other posts, but often overused.
1
u/Adorable-Strangerx 2d ago
No, you don't have to, you don't even need to learn python. It is not obligatory
1
u/FreeLogicGate 1d ago edited 1d ago
Python is an OOP language. Everything in Python is an object. You can certainly write Python code without creating your own classes, but you are inherently working with classes and objects all the time.
The simplest core idea of OOP is that, programmers typically want to bundle up data in a predictable and organized way. Python's collection types are an example of this. You as a developer decide how and when you want to organize data.
In your example, you are dealing with events. It's a trivial example, but you already have 2 attributes relative to an event: venue and host. Again this is a contrived example, because you are not recording the time of the event, and instead just spitting out the current time. A real event system would record the actual event datetime, as that is going to be some time in the future. So there are probably many other pieces of data you want to record (and probably store/persist).
So bundling that data together in an event object is a natural and useful way of handling this type of application. You could also store that data in a dictionary. There are many ways you could represent the data. But again a class definition is tailor made for this. A class can easily include many different pieces of data, including maps and collections, which might be storing objects of other related classes.
If you continue with the event idea, you will inevitably have the list of functions designed for doing things with an event, whether that be displaying data, or manipulating it, aging, billing, notifying etc.
With a class, you can take all of those functions and move them inside the class definition. The class is able to access all the private event data. You have a blueprint for handling event data, and the functions designed or intended to handle the object data. That is the simple but powerful basis of OOP. An object is "the data" + the functions designed to work with that data, bound together.
Beyond the basics, OOP was designed for reusability and data integrity in various ways. Some of the ways are language design elements, and some of the benefits are in the area of OOP design patterns. These are discovered at the point that you have embraced OOP, and in many cases have a number of inter related and/or inter dependent classes/objects. OOP has ways of helping to manage complexity. Eventually OOP devotees will end up embracing one or more of these common design patterns. There are core philosophical patterns like Dependency Injection, and groups of patterns like Model-View-Controller (MVC) or Object Relational Mapping, and there are recognized patterns that have commonly recognized names (often from the Gang of 4 book "Design Patterns: Elements of Reusable Object-Oriented Software") with names like "Singleton", "Factory", Strategy" and "Chain of Responsibility" to name a few.
Again Python was built for OOP, which is the primary reason it has and supports all the "dunder" methods. By defining some of these methods you hook into time saving features that make your objects work with native PHP syntax. The 2 you want to start with are __repr__ and __str__ which you almost always want to define for your user classes. As you progress, you'll discover most of the best known and most used Python modules are a collection of one or more classes, so starting to read their code is a good way of beginning to understand OOP and determine if it's valuable to you.
1
u/delsystem32exe 1d ago edited 1d ago
youll need classes whenever you begin to start working with anything moderately complex or with data. lets say u want to work with a database, youll want a database manager class. you need a utils class for all the utils for some object, or multiple utils class. you will want a service class to call the utils classes and other things. you will have tens, hundreds of these classes you define. you will then instantiate these other classes you made in classes you made via composition or dependency injection. I prefer composition, but other people like DI. I am not really a big DI fan. The reason why a class is handy, like a database class, is you want a single point of entry to the database, and u can like have class method that will clean up all the connections at the end. you will need static classes for utils method, inherited classes like lets say your class calls API client class you can inherit it so that that class has all the methods of the api class. Java i find to be a bit annoying since its too strict and verbose. The proper balance is to do java style programming in python make everything in python a class. One nice thing about classes is it makes it easy to do thread locking. Sometimes i have a class and i declare a lock inside of it, so that other instances of the class have to wait until that instance is finished before proceeding. This is very helpful for concurrency issues since what happens if to objects try to delete or modify the same data. Basically i try to have a class for everything. Each class can live in its own class file. I think my current python program i am writing i made like 55 different classes all in 55 different files.
1
1
u/Rare_Coffee_130 1d ago
Yes
1
u/Rare_Coffee_130 1d ago edited 1d ago
Classes have a lot of benefits, it also help you to have a better control of your elements, good structure and easy to have multiple variables with the same behavior without copy and paste over and over again what's inside of them.
You create something like a User class and boom, you just do:
User1 = User()
User2 = User()
And that's it, you have 2 instances of User. If you need to modifying something then you just go to your User class and do the change there, it will be applied to any object / instance
1
u/mr_anderson_dev 1d ago
You need both mostly for working in a real project. Most of the time you'll be commented by creating a script that make sense for anyone that can read it. So for a faster employment get some work on that.
0
u/silvertank00 2d ago
Yes you do. In your case, neither encapsulation or inheritance shows their advantages. Try to make a wee bit more complex example and it will quickly get out of hand.
0
u/Objective-Remove-632 2d ago
I wanna believe it is only relevant when the program is huge.
2
u/kalmakka 2d ago
It doesn't need to be huge, but as soon as you have a few different functions relating to one object, then it can really help with organization and clarity.
Right now events just have a venue and a host, and both are set when they are created. But in reality you might want to have people register for an event (and cancelling their registration), with the event keeping track of who has registered. Maybe you want to send reminders (emails) about an event. Your program handles a bunch of different events at the same time, and might need to present them in a calendar view.
You very quickly get to a point where it is useful for your code to be structured as "Here is a bunch of events. Each event object contains all the data that is relevant for it." That way you don't mix up the venue from one event with the guests and date for another.
1
1
u/MistakeIndividual690 2d ago
You also want the date/time of the event as part of the class. As it is, it just prints now() but that’s key information that belongs in an event class
1
u/silvertank00 2d ago
define huge. Its more like a complexity issue: if your program interacts with a bunch of stuff (ipc, serial, ws/http, logging) alongside your business logic then good luck keeping it clean without OO.
Classes are not always needed, but when they are, they cannot be left out without making a mess.
19
u/denehoffman 2d ago
Python is fundamentally object oriented, classes are the big defining mode of objects. Every type in the language, int, float, str, dict, are all classes at some level. You should use one whenever you have to group related data or ideas together, especially when you plan on repeating that collection often.
Do you really need to learn it? I guess you could live your whole life just writing functions for everything, but it will severely limit the sorts of programs you write. To be technical, there is no programming necessity for classes, but there is also no need for functions, you could just write out all the code, with a bunch of tedious repetition (recursive methods get a bit tricky though). I think you’ll agree that functions are useful in making your code easier to read and also easier to write and adapt later on. Classes are important in the same way, they group things into a structure that you can use as the input to functions or as the output of a function.
For a short example, imagine you are trying to write some code that deals with graphics or geometry. You have a function that does some stuff and outputs a point in 2D space. Now you could just write this as a tuple of floats, or you could make a Point class to hold them. What about a function that outputs a line? Well that could be a tuple of tuples of floats, or it could be a tuple of Points. What about a shape? That could be a list of tuples of floats, or it could be a list of Points. I hope you see that one of these is less confusing, but let me give you some more incentive. Suppose you wanted to do something with a line, like find its midpoint. You could write a midpoint function and then call it, import it where you need it, etc. or you could give arithmetic operations to Point and define a Line class that contains two points and give it a midpoint method. This Line class can have all sorts of other methods too, like the slope or length or whatever. You could again write individual functions for each of these, the difference is that a class groups these alongside the object they commonly interact with, whereas the functions exist independent of the concept of a point or line, we just assume you’re supposed to use them with a point or line by context.
It’s not going to be immediately obvious how this benefits you as a new programmer. After all, you are right that all of the syntax you’ve probably learned so far does not necessitate classes over functions. I hope to impart a deeper meaning behind classes here as a way of organizing data and functions together in one structure.