w1coding.comAll tutorials

Python Classes

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

Python Classes and Objects

Classes and objects are the foundation of Object-Oriented Programming (OOP). A class is a blueprint for creating objects, and an object is an instance of a class.

Creating a Class

To create a class, you use the class keyword:

      
        class Person:
            def __init__(self, name, age):
                self.name = name
                self.age = age
            
            def greet(self):
                print(f"Hello, my name is {self.name} and I am {self.age} years old.")
        
        # Create an object of the class
        person1 = Person("Alice", 25)
        person1.greet()
      
    

The __init__ method is the constructor that initializes an object, and the greet method is a function that belongs to the class.

Activity

Try It Yourself!

Create a Car class with attributes make and model, and a method that prints the car's information.

Quick Quiz

Quick Quiz

  1. What is the difference between a class and an object?
  2. What is the purpose of the __init__ method in Python classes?

Answers: A class is a blueprint for creating objects, while an object is an instance of the class. The __init__ method initializes the attributes of the object when it is created.