Classes and objects are fundamental concepts in Object-Oriented Programming. A class is a blueprint or a template for creating objects, which are instances of the class. An object is an instance of a class, and it has its own set of properties and methods.
In Python, we define a class using the class keyword. Here is an example of a simple class:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
In this example, we define a Dog the class that has a constructor method __init__ which takes two arguments name and breed and initializes the name and breed attributes of the object. We also define a method bark which prints “Woof!” to the console.
To create an instance of this class, we can simply call the class and pass the required arguments to the constructor:
my_dog = Dog("Buddy", "Golden Retriever")
This creates an instance of the Dog class with name set to “Buddy” and breed set to “Golden Retriever”. We can then call the bark method on my_dog:
my_dog.bark() # Output: "Woof!"