Class and Object
Class and Object
• def drive(self):
• print(f"{self.brand} is driving at {self.speed} km/h")
• def drive(self):
• print(f"{self.brand} is driving at {self.speed} km/h")
• def greet(self):
• print(f"Hello, my name is {self.name} and I am {self.age} years old.")
• # Creating an object
• p1 = Person("Alice", 30)
• p1.greet()
Step-by-Step Explanation
• Here's what happens step-by-step:
• Python sees Person("Alice", 30) →
• So it calls the __init__ method.
• It creates a new object in memory (let's say at location X).
• It passes this new object as self, and "Alice" as name, and 30 as age.
• Inside __init__, it stores:self.name = "Alice"self.age = 30
• The object is stored in the variable p1.
Step-by-Step Explanation
•init__ assigns the values when an object is created.
•self holds these values inside the object so they can be
accessed later.
Think of it Like This:
Imagine you're filling out a name tag at an event:
1.__init__ is like the process of writing your name and age on the tag.
2.self is like the tag itself that keeps holding your name and age so
others can see it.
Super Simple Takeaway✅
• self makes sure that each object keeps its own data.✅ Without self, all
objects would lose their unique values!
Step-by-Step Explanation
• Step 3: The self Keywordself refers to the current object being
created.Think of it as saying "this object".Inside the class, we write
self.name, self.age to store the values inside the object.
• Step 4: Creating an Object
• p1 = Person("Alice", 30)
Step-by-Step Explanation
• Step 5: Using the Object
• p1.greet()
• It calls the method greet on object p1.Inside greet, self.name refers to
"Alice" and self.age refers to 30.So it prints:👉 Hello, my name is Alice
and I am 30 years old.
Step-by-Step Explanation