Python is an object-oriented Language and it is a powerful paradigm that can help you write modular and organized code. In Python, everything is an object. Major Principles of Object-Oriented Programming are-
- Class
- Object
- Method
- Inheritance
- Polymorphism
- Data Abstraction
- Encapsulation
CLASS
A class is a blueprint or template for creating objects. Objects are instances of classes. You can define a class using the class
keyword. It defines a set of attributes(data) and methods(functions) that the object created from the class.
OBJECTS
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods
class Dog:
def __init__ (self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
my_dog = Dog("Buddy", 3) #object is created by calling the class
print(my_dog.name) #Accessing the attributes
print(my_dog.age)
my_dog.bark()
# Output
Buddy
3
Woof!
In the above example, name and age are the attributes of the class ‘Dog’ .
Methods are the functions that are defined inside the class. Here ‘bark’ is a method of the ‘Dog’ class.
The init method is a special method that gets called when an object is created from the class, it is used to initialize the attributes of the object.