How to Instantiate a Class in Python: Concepts Made Simple

How to Instantiate a Class in Python: Concepts Made Simple


You need to know OOPs concepts if you’re a programmer, they help you build a good understanding of programming paradigms. As a Python programmer, I want to walk you through the process of instantiating (creating an instance of) a class in Python. This is an essential concept to understand as you build more complex programs using object-oriented programming, not just in python obviously. So, let’s get to it and see how to instantiate a class in Python.

Classes in Python

Let’s first see what are classes in Python.

google.com, pub-1688327249268695, DIRECT, f08c47fec0942fa0

Classes in Python are a way of grouping related properties and behaviors into reusable bundles of code in Python. They serve as blueprints for creating programmatic representations of real-world objects.

For example, we can use classes to define objects like a Person, Car, Cat, or Employee. Classes allow us to model elements in our programs similar to how objects work in the real world.

Here’s how you can define a class in Python, after that we’ll look at how to instantiate a class in python:

Python

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

How to Instantiate a Class in Python?

In the previous section we discussed what are classes in python, now we will look into the instantiation part of the classes. Instantiation are a way to initialize a class or form an object of a class.

Here’s the syntax of instantiating a class in Python:

object_name = Class(arguments)

We can see the 3 things in the statement:

  1. object_name – It refers to the object variable that you need to form as a class instance.
  2. Class – Class is the actual class name we defined before.
  3. arguments– Arguments are required initial arguments that one needs to pass while initializing a class.

The arguments are required only when the are defined in __init__ method inside the class.

Now Let’s define a new User class, which we are going to instantiate later and work with it.

Python

class User:
    def print_name(self):
        username = "Sachin Singh"
        return username

In the above code, we defined a class named User which carries only one method named print_name(). This method has 1 username variable having value “Sachin Singh” and then we return the same username value.

Okay, so we’ve talked through the class definition. Now let’s instantiate this class in Python:

Python

user1 = User()
print(user1.print_name())

Now that’s how we instantiate a class in python, let’s see what we did.

Look at the syntax we defined above and compare it with this code. We can see a object_name written as user1 and on the right hand side we got a Class named User(). Notice, that in this case we didn’t defined any __init__ method in our class so we are not adding those arguments here, but we will get back to that in a while, don’t worry.

After that we just added a print() for the object user1 calling the class method named print_name(), as we instantiated the class with user1 obj, now user1 will have all the properties of User class and hence we can call the print_name() method from user1.

The output will be:

Output: Sachin Singh

This was instantiating a class without required arguments. Now we are going to instantiate a class with required arguments by defining the __init__ method in class.

Let’s see how to do that:

Python

class User:
    def __init__(self, username): # Added a __init__ method with username parameter.
        self.username = username

    def print_name(self):
        return self.username

You can notice in the above code we added a new __init__ method in our User class, which takes a parameter named username. So, now we need to pass it while instantiating the User class. After that we can see that we used something like self.username which got assigned the value of our username parameter. Now why is that used?

Well, the self.username will basically help us in accessing the username variable globally, hence every method can get access to it by just using the self.username notation. As you can in our print_name() method rather than assigning a username value as we did previously, we now just simply return self.username. Looks good, doesn’t it?

Similar Read – How to Convert a List to JSON Python? Best Simple Technique

It’s time to instantiate this class in Python:

Python

user1 = User("Sachin Singh")
print(user.print_name())

Well well, see you we did there. We passed the “Sachin Singh” as an argument to our User class which was needed by the __init__ method of our class. Post that, we just printed the name using the .print_name() method.

Guess the output now?

Output: Sachin Singh

It’s the same output! But it now looks more professional and dynamic! Let’s try some more things.

Python

class User:
    def __init__(self, username, city, age):
        self.username = username
        self.city = city
        self.age = age

    def print_name(self):
        return self.username

    def introduce(self):
        intro_string = f"Hi! My name is {self.username}. I live in {self.city} and my age is {self.age}."
        return intro_string

I added some more parameters here such as city and age. Moreover, i added a new method named introduce() which builds an intro_string that gets return with all the new parameters.

Similar Read – Using Python Retry Decorator to Implement Retry Mechanism

Python

user = User("Sachin Singh", "Delhi", 22)
print(user.introduce())

Output: Hi! My name is Sachin Singh. I live in Delhi and my age is 22.

As Expected, right? Well that was all the basic coverage of how to instantiate a class in Python.

Conclusion

To Sum up, we have looked at the class definitions and syntax. We tried defining a new class named User() and made two approaches to using it: One is without __init__ method and one is with it. We tried tweaking our class a little bit to explore the use of self keyword. You can try declaring your own class now and implement some of your required stuff. I hope you got a basic overview of how to instantiate a class in python!

Also Read:

FAQs

What is the purpose of the init() method?

The init() method is called automatically when an object is instantiated. Its purpose is to initialize the attributes of a class. This method accepts arguments that can be used to set the initial state of a newly created object, allowing it to store data specific to that instance.

What is the difference between a class and an instance?

A class is a blueprint or template that defines the properties and methods shared by all objects of that type. An instance is a specific object that is created from a particular class. The class acts like a mold and the instances are the objects popped out of that mold. All instances of a given class have the same methods but contain data (attribute values) that are specific to that instance.

How many instances can I create from one class?

You can create unlimited instances from a single class definition in Python. For example, you can instantiate millions of Person objects from the Person class because the class is just the blueprint. Each person instance can store different data (like different names and ages) but will be created from the same Person class.



Source link