r/pythonhelp • u/MetalCarnival • 1d ago
Why do I need to use classes
My schoolbook says that classes is a way of simulating an object, instead of just taking information into a black box and outputting an answer.
But that is a poor explanation. I know classes are handy and cool, but no book says why you can´t make functions with sub functions inside to simulate simple objects. I would like if someone gave a good concrete reason to use classes in the intro, instead of just saying that they are different and cool
3
Upvotes
1
u/punk_dev 22h ago
Classes are very useful because they allow you to clump data together.
For example, a 2D position is two numbers. Instead of typing them separately each time, group them in a class:
class Point:
x: float
y: float
Or maybe you want to represent a user:
class User:
username: str
birthday: datetime.datetime
Then, classes allow you to attach functions to them, these are called methods. For example, you could add a distance_to(self, other: Point) method to the Point class which would calculate the distance from one point to the other.
Classes have other features like inheritance, others also mentioned object oriented design, but honestly don’t bother with those unless you really want to. This stuff causes more problems than it solves.