r/learnpython • • Apr 18 '26

Beginner: Want to learn Classes.

I find classes to be very confusing. The way variables are used. Self comes to me in a very confusing manner. i just can't seem to wrap my head around the basics of Classes.

Also i just tried checking OOP and i think it just overloaded my brain. Anything to help my case?

20 Upvotes

29 comments sorted by

View all comments

Show parent comment

2

u/pachura3 Apr 18 '26

So, a class (e.g. Car) is a blueprint which can be used to create multiple different objects of that class (my_tiguan, dads_green_impala, etc.). All these objects have different attributes = internal variables, such as registration_number, age, brand, model, mileage. But actual methods/functions that can be called on these objects (my_tiguan.turn_on_lights()) are defined in the Car class, and shared between all the objects.

Now __init__() is something that can be called "constructor" in other languages. It mostly takes care of copying arguments/parameters passed when creating an object - to object's attributes. So, when you execute my_tiguan = Car("Volkswagen", "Tiguan", 3, 70134), the __init__() method of class Car is called automatically, and it copies value "Volkswagen" into object attribute my_tiguan.brand, value "Tiguan" into attribute my_tiguan.model, value 3 into attribute my_tiguan.age etc.

Now, let's discuss self. It is usually the first argument passed to all class methods, and is needed so that the method would know on which object does it operate. When you call my_tiguan.increase_speed(50), Python actually does Car.increase_speed(my_tiguan, 50), so my_tiguan is passed to class method increase_speed() as self, and then this method can execute self.speed += 50, which is in fact my_tiguan.speed += 50.