Home / Questions / How do you create a class in Python?
Explanatory Question

How do you create a class in Python?

👁 235 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

To create a class in Python, you use the class keyword followed by the name of the class. The body of the class is indented under the class definition and contains variables (also known as attributes) and methods that make up the class.

Here's an example of a simple class in Python:


class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        print("Woof!")

my_dog = Dog("Max", "Labrador")
print(my_dog.name) # Max
my_dog.bark() # Woof!

In this example, the class Dog has two attributes, name and breed, and one method, bark. The __init__ method is a special method called a constructor, and it is called automatically when an object of the class is created. The self parameter refers to the object being created, and it is used to access the attributes and methods of the class.