r/learnpython • u/Forward-Ride2950 • 9d 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
3
u/the_milkman01 9d ago
they way i always understand it
a class is a a blueprint of how youre object is going to be like ,
an object is created from a class , this example car1 , but you can also have car2 car3 etc
all those objects are instances of the class car
1
2
7
u/Beginning-Passion439 9d ago
Yep, that's right. Object and instance are the same thing, "instance" just names the class too, like car1 is an instance of Car.
4
u/xenomachina xenomachina 9d ago
Yeah, exactly. "object" and "instance" are almost but not quite synonyms. Every instance of a class is an object. Every object is an instance of some class. But you wouldn't call an object an "instance" unless the class you're saying it's an instance of was also known or stated.
Similarly, one might say that every person is a member of one or more groups. But to call a person a "member" without the group you're referring to being known or stated would seem really weird/awkward.
2
u/SharkSymphony 8d ago
I think this gets at the nuance. Instances are objects and v/v, but when you say instance you're highlighting the object's relation to some class (typically, the class that was used to create it). When you're talking about objects, you might not care in the moment what classes they're instances of.
6
1
u/backfire10z 9d ago edited 9d ago
Yeah, looks about right.
The `self` parameter is automatically passed in by Python when you call a method of the instance.
For example, suppose your Car class also had `def print_color(self): print(self.color)`. You would call `car1.print_color()`, and then `self` would be `car1`.
You can actually also do `Car.print_color(car1)`, but that’s not idiomatic and there are some edge cases where this may cause unexpected behavior.
1
1
1
u/Classic-Rate-5104 9d ago
"self" is only conventional, you can also use "this" or "myself" or whatever.
1
1
u/NothingWasDelivered 9d ago
Yeah, that’s about right. An object is kind of a programming abstraction that lets you combine properties and behaviors together. In Python, everything is an object, but that’s not the case in every programming language. In many languages, an integer, for example, is what’s called a primitive. In those languages, 4 has no properties, it has no methods or behaviors. It’s the representation of the number 4 in memory, for example.
1
1
u/jmacey 9d 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"
1
3
u/Discordbothost 9d ago
yeah youve basically got it. in python people use object and instance as the same thing — car1 is both. class = blueprint, car1 = one car built from it, self inside a method just means "this particular car". the only wrinkle is every value in python is an object (even 3 and "hi"), so "object" also gets used more loosely outside OOP talk.
2
u/vlcod 9d ago
This is not wrong, but a little more complicated than necessary. Specifically: "object" and "instance" are essentially synonyms (they mean the same thing).
A class describes the concept of a thing. For example, if I talk about class "Elephant", I am talking about the idea of an elephant, the whole concept of it. And I can make statements about them: Elephants are grey. Elephants have trunks.
If I make a statement about the class Elephant, this applies to all elephants.
An elephant object is one particular specific elephant. If you go to the zoo, and there are four elephants in the enclosure, you have four objects. Four elephant object, or objects of class elephant.
They can have different attribute details (one is small, one is big, one has a broken tusk), but they are all objects of class elephant, so everything that is true about the class is true about every object of the class.
When we want to emphasise that on object is of a specific class, we often say "they object is an instance of Elephant". It just emphasises the class-object relationship, but saying "instance of class Elephant" or "object of class Elephant" is the same thing. So object and instance is the same.
In modelling terms, the class describes the whole set of objects (what attributes they hold, what they can do (methods)). In programming language terms, classes are often referred to as a blueprint, because they define what each object created from them looks like, and what it can do.
From one class, you can have many objects (or none).
3
u/StrayFeral
9d ago
•
The class is the blueprint of which we can instantiate many objects. The class could have parent classes. The class could have child classes (subclasses). A class represents only a design. This is why the class is not alive. The class have two things very generally speaking - methods and properties. The properties are just variables which belong to the class. Methods are just functions which belong to the class.
Example:
We could have a class Vehicle. This is very generic. A vehicles can have properties. For example a vehicle can have a color, wheels which could vary by number but are usually 4. A vehicle could move forward, backwards, the wheels could turn left and right. The vehicle could stop (if moving).
class Vehicle:
def init(self):
self.color = "red"
self._gear = "P" # vehicle is parked
self.speed = 0 # mph/kmh
self.odometer = 0 # whoa, a brand new vehicle
self._engine_started = False # vehicle is parked
def change_gear(self, new_gear):
self._gear = new_gear
def start_the_engine(self):
self._engine_started = True
def stop_the_engine(self):
self._engine_started = False
def accelerate(self):
pass
def brake(self):
passPlease note - some methods have only the keyword "pass" - this means we don't know yet what the method would do and we would code it later.
Then we could have class Car(Vehicle). The car itself is a vehicle - this is true. But Car(Vehicle) tells Python that the car is a type of vehicle. Then we can do a class Truck(Vehicle). Also class Motorcycle(Vehicle). Why not a class Van(Vehicle). Because the vans and cars and trucks are all vehicles, but the van is not a car, neither a truck - they are different vehicles, still all are vehicles.
Than we could have a class FamilyCar(Car), also class SportsCar(Car), class Dragster(Car) because these are all type of cars. However very generally said the car is also a vehicle. So all cars - FamilyCar, SportsCar and Dragster are vehicles too - they are also children of class Vehicle.
For this reason, despite we declared FamilyCar as a child of Car, even if we don't type a single line of code, FamilyCar automatically would have method brake() and method accelerate() and everything else from Vehicle.
If you understand what i just described, you understand what is a class, but also very important - what is "inheritance".
Instantiation is the process of making a class alive. By instantiating we create objects.
Object is an instance of a class. Objects are alive.
So if we do
my_car = Van
his_car = SportsCar
her_car = FamilyCar
my_car.start_the_engine()
my_car.change_gear("1")
my_car.accelerate() # off we go!
my_car.brake()
my_car.change_gear("P") # we're parking
my_car.stop_the_engine()but if we do nothing for some time Python would throw these into the garbage, so the garbage collector would come to get these (this is like a garbage truck for objects). Also at the end of a Python program, the garbage collector would come for all objects. Because the memory needs to be freed.
Also in this example my_car, his_car and her_car are all objects and are all instances of classes.
End of story.
The class is just a dead blueprint. The object is a live instance of the class. Classes could have parents and could have child classes and this is called inheritance. All children inherit all properties and methods of the parents.
1
u/StrayFeral 9d ago
Important is not to thing is specific implementation. Important is to start abstract. So you start with a car. But the car is a very specific implementation of a vehicle. So I started with a vehicle, declared some other vehicles, like vans and trucks and then declared a car and what cars could exist.
1
1
u/cdcformatc 9d ago
an object is a generic bundle of state(data/variables) and behavior (methods).
a class is a specification that is used as a blueprint to create instances of objects.
an instance is a specific object, created using the class specification.
self is just a reference to the instance itself. when the program calls a method of a class, that method needs to know what object it is supposed to use.
1
1
u/acfot 9d ago
You're mostly right, yeah. The class is the blueprint, that's spot on. Where I'd tweak it is the object vs instance bit, they're actually the same thing in Python, an instance of a class is an object, so car1 is both at once. The way I think about it is the class is the recipe and car1 is the actual car you built from it, you could make car2 the same way and it'd be a different object with its own color. And self is just Python's way of saying "this particular car", so inside a method self.color means car1's color, not the class's. It clicked for me once I made two cars with different colors and saw they didn't interfere with each other.
1
u/2hands10fingers Experienced Pythonista 9d ago
Self is only something you can access if an object is instantiated, it’s a way to access and change the properties and methods as they’re currently stored within the object you’re referencing. You can create a class that never needs to be instantiated and only has methods that process external data without accessing itself.
6
u/ninhaomah 9d ago
Just curious. The textbook or the site you are reading defines what is an object as well ?
Class ok. Instance ok. But object ?