Show List

Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects". In OOP, objects are instances of classes, which are essentially user-defined data types that encapsulate data and behavior.

In Python, you can define a class using the class keyword. Here is an example of how to define a simple class in Python:

ruby
Copy code
class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def bark(self): print("Woof!")

In this example, the Dog class is defined with two instance variables (name and breed) and one method (bark). The __init__ method is a special method that is automatically called when an object of the class is created. It is used to initialize the object's instance variables. The self parameter is a reference to the object being created, and it is used to access the object's instance variables.

Here is an example of how to create an object of the Dog class and use its methods:

scss
Copy code
dog = Dog("Buddy", "Golden Retriever") print(dog.name) print(dog.breed) dog.bark()

In this example, an object of the Dog class is created with the name "Buddy" and the breed "Golden Retriever". The object's instance variables are then accessed and the bark method is called.

In Python, classes can inherit from other classes. This allows you to create a new class that is a subclass of an existing class, inheriting its methods and variables. Here is an example of how to use inheritance in Python:

scss
Copy code
class GoldenRetriever(Dog): def fetch(self): print("Fetching the ball!") dog = GoldenRetriever("Buddy", "Golden Retriever") dog.bark() dog.fetch()

In this example, a new class GoldenRetriever is defined as a subclass of the Dog class. The GoldenRetriever class inherits the bark method from the Dog class and adds a new method fetch. When an object of the GoldenRetriever class is created and its methods are called, it demonstrates that it has inherited the methods from its parent class.


    Leave a Comment


  • captcha text