File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Day 17: Introduction to Object-Oriented Programming (OOP) - Classes and Objects
2+
3+ # In OOP, a Class is a blueprint for creating objects.
4+ # An Object is an instance of a Class.
5+
6+ # 1. Define a Class
7+ class Dog :
8+ # The __init__ method is a special method called a constructor.
9+ # It runs whenever a new object is created from the class.
10+ # 'self' refers to the object itself.
11+ def __init__ (self , name , breed ):
12+ # These are attributes (data) of our object.
13+ self .name = name
14+ self .breed = breed
15+ self .is_hungry = True
16+
17+ # 2. Define a Method
18+ # A method is a function that belongs to a class.
19+ def speak (self ):
20+ print (f"{ self .name } says Woof!" )
21+
22+ def eat (self ):
23+ if self .is_hungry :
24+ print (f"{ self .name } is eating now." )
25+ self .is_hungry = False
26+ else :
27+ print (f"{ self .name } is not hungry." )
28+
29+ # 3. Create Objects (Instances of the Class)
30+ # We create objects by calling the class name like a function.
31+ my_dog = Dog ("Buddy" , "Golden Retriever" )
32+ your_dog = Dog ("Lucy" , "Poodle" )
33+
34+ # 4. Access Attributes and Call Methods
35+ print (f"My dog's name is { my_dog .name } and he is a { my_dog .breed } ." )
36+ my_dog .speak ()
37+
38+ print (f"Your dog's name is { your_dog .name } and she is a { your_dog .breed } ." )
39+ your_dog .speak ()
40+
41+ # Let's interact with our objects
42+ my_dog .eat ()
43+ my_dog .eat () # Calling the method again to show attribute change
You can’t perform that action at this time.
0 commit comments