A class is a blueprint for creating objects. It defines the attributes (data) and methods (functions) that its objects will have. Objects are instances of a class and can hold their own unique data while sharing the behavior defined by the class.
__init__(): A special initializer method that runs automatically when an object is created.self: Refers to the current object instance; used to access attributes and methods.name, breed).bark()).A basic Python class is defined using the class keyword. The __init__() method initializes the attributes for each new object created from the class.
When you create an object (also called instantiating a class), Python calls __init__() automatically and passes the arguments you provide to it.
Here is a simple Dog class with two attributes (name and breed) and one method (bark()).
class Dog:
def __init__(self, name, breed):
self.name = name # instance attribute
self.breed = breed # instance attribute
def bark(self):
print(f"{self.name} is barking!")
# Creating an object
dog1 = Dog("Buddy", "Golden Retriever")
Once an object is created, you can access its attributes and call its methods using the dot (.) operator.
print(dog1.name) # Buddy
print(dog1.breed) # Golden Retriever
dog1.bark() # Buddy is barking!
You can create many objects from the same class. Each object has its own data but shares the structure and behavior defined by the class.
dog2 = Dog("Charlie", "Beagle")
dog3 = Dog("Max", "German Shepherd")
dog2.bark() # Charlie is barking!
dog3.bark() # Max is barking!
You can think of a class as a blueprint and an object as the actual thing built from it:
If you run all of the code examples together, you would see something like:
# Expected output when running all the code above
Buddy
Golden Retriever
Buddy is barking!
Charlie is barking!
Max is barking!
Each call to bark() prints a message that includes the name of the specific dog object. Even though all objects are created from the same Dog class, they carry their own values for name and breed.
self as the first parameter in methods defined inside a class.self.name) belong to each object separately.Car class with attributes brand and year. Then make three different car objects.Student class with a method study() and call it using two different student objects.Animal class and create different animal objects with their names.start(), stop(), eat()) to your classes.