Object Oriented Programming in Python?

Photo by RetroSupply on Unsplash

Object Oriented Programming in Python?

·

2 min read

You might have come across the concept of object-oriented programming when learning Python. This article will cover how to instantiate an object in python, the init function in Python and the concept of inheritance in Python. Lets go through the example of creating a class then creating an object of that class.

class Dog:
    x = 5

In the above example, we have created an example class called Dog. This example class has a property named x.

Lets look at another example called Dog. Lets create an object of this class. In this example, we have created an object p1 of the class Dog.

p1 = Dog()
print(p1.x)

We can use the created object p1 to access the class property x. We are going to discuss another example called init function. The init function in any kind of created class is referred to as a constructor.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


p1 = Person("John Doe", 30)

print(p1.name)  # John Doe
print(p1.age)  # 30

In the example above, the __init__() method is called when an object is created. The init method takes two arguments, John Doe and the age of 30. The name attribute is set to John Doe and the age attribute is set to 30. The created object p1, has two attributes, name and age.

Here are some additional things to keep in mind about the __init__() method:

  • The __init__() method is always called with the object's arguments as its parameters.

  • The __init__() method can be used to initialize any number of attributes.

  • The __init__() method can be used to perform any other necessary initialization tasks.

Did you find this article valuable?

Support Iqra by becoming a sponsor. Any amount is appreciated!