✏️ Explanatory Question

How do you create an instance of a class in Python?

👁 227 Views
📘 Detailed Answer
227
Total Views
10
Related Qs
0%
Progress
💡

Answer with Explanation

To create an instance of a class in Python, you call the class as if it were a function and pass any necessary arguments to its constructor. The constructor is a special method named __init__ that gets called automatically when you create an instance of the class.

Here's an example of creating an instance of a 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 Dog class is called with the arguments "Max" and `"Labrador"