r/learnpython • • 19d ago

Trying to understand Class, Object, Instance, and self in Python. Is my understanding correct?

I'm currently learning OOP in Python and wrote down some questions regarding object and instance for following code

class Car:
    def __init__(self, color):
        self.color = color

car1 = Car("Red")```

 1) what is class ?

ans :-  a class is an blueprint for thing i want to make.

2) what is object ?

 ans:-  an object is a container that contains properties and behaviours like car1 is object saying that car should be red color

3) what are instances ?

 ans:-  an instance is refers to that specific object in this case car1 is object and also an instance
when we pass self parameter self become car1 cause self points towards that instance
50 Upvotes

33 comments sorted by

View all comments

1

u/jmacey 19d ago

typically I would say the class is the template as you say and that an object is an instance of a class. An easy way to understand what self is is to look at the code here

>>> class A :
...     def __init__(self) :
...         print(self)
...
>>> a=A()
<__main__.A object at 0x104ceb380>
>>> hex(id(a))
'0x104ceb380'
>>>

When you create anything in python and assign it to a variable. What you are actually doing is putting a label on a memory address. When you instantiate a class the same thing is happening. The class is given a memory address. When you do anything with the class such as call a method that memory address is passed in and give the name self (by convention). So it basically means "this memory address" or "this instance of my particular class"