What You Will Learn
Beginner
- What OOP is and why it exists
- How to define a class and create objects
- The __init__ method and self
A class is a blueprint; objects are instances created from it
Terminalpython
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
# Create objects (instances)
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
print(dog1.name) # Buddy
print(dog1.bark()) # Buddy says Woof!
print(dog2.bark()) # Max says Woof!Key terms
Class: blueprint. Object: instance. Attribute: data (self.name). Method: behavior (def bark). __init__: constructor, runs when object is created. self: refers to the current object.Practical Exercise
Define a class Cat with __init__(name, color)
Add a method meow() that returns a string
Create two Cat objects
Call meow() on each object
Access attributes: print(cat1.name)
Key Takeaways
- Class = blueprint. Object = instance created from class.
- __init__ is the constructor - runs when object is created.
- self refers to the current object (like 'this' in Java).
- Attributes = data (self.name). Methods = behavior (def bark).
- Create objects: obj = ClassName(args).
Comments
Comments
Post a Comment