|
| 1 | +# `042` understanding classes |
| 2 | + |
| 3 | +In Python, a class is a structure that allows you to organize and encapsulate related data and functionalities. Classes are a fundamental feature of object-oriented programming (OOP), a programming paradigm that uses objects to model and organize code. |
| 4 | + |
| 5 | +In simple terms, a class is like a blueprint or a template for creating objects. An object is a specific instance of a class that has associated attributes (data) and methods (functions). Attributes represent the characteristics of the object, and methods represent the actions that the object can perform. |
| 6 | + |
| 7 | +## 📎 Example: |
| 8 | + |
| 9 | +```py |
| 10 | +class Student: |
| 11 | + def __init__(self, name, age, grade): # These are its attributes |
| 12 | + self.name = name |
| 13 | + self.age = age |
| 14 | + self.grade = grade |
| 15 | + |
| 16 | + def introduce(self): # This is a method |
| 17 | + print(f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}.") |
| 18 | + |
| 19 | + def study(self, hours): # This is another method |
| 20 | + print(f"{self.name} is studying for {hours} hours.") |
| 21 | + self.grade += hours * 0.5 |
| 22 | + print(f"After studying, {self.name}'s new grade is {self.grade}.") |
| 23 | + |
| 24 | +student1 = Student("Ana", 20, 80) |
| 25 | + |
| 26 | +student1.introduce() |
| 27 | +student1.study(3) |
| 28 | +``` |
| 29 | + |
| 30 | +In this code: |
| 31 | + |
| 32 | ++ The `Student` class has an `__init__` method to initialize the attributes *name*, *age*, and *grade* of the student. |
| 33 | ++ `introduce` is a method that prints a message introducing the student. |
| 34 | ++ `study` is a method that simulates the act of studying and updates the student's grade. |
| 35 | + |
| 36 | +## 📝 Instructions: |
| 37 | + |
| 38 | +1. To complete this exercise, copy the provided code from the example and paste it into your `app.py` file. Execute the code and test its functionality. Experiment with modifying different aspects of the code to observe how it behaves. This hands-on approach will help you understand the structure and behavior of the `Student` class. Once you have familiarized yourself with the code and its effects, feel free to proceed to the next exercise. |
| 39 | + |
| 40 | +## 💡 Hints: |
| 41 | + |
| 42 | ++ Read about the `__init__` built-in function: https://www.w3schools.com/python/gloss_python_class_init.asp |
| 43 | + |
| 44 | ++ If you find yourself wondering about the role of the `self` keyword in Python classes, take a moment to visit the following link for a detailed explanation: [Understanding the 'self' Parameter](https://www.geeksforgeeks.org/self-in-python-class/) |
0 commit comments