How to create class objects in Python?


In Python, classes are like blueprints for creating objects. Once you define a class, you can create objects (also called instances) based on that class. Here are four ways to create class objects in Python:

Creating a Class and an Instance

Example

In this example, we define a class called `MyClass` using the `class` keyword. We then create an instance of the class called `obj` using parentheses `()` after the class name. This creates an empty object that is an instance of the class.

class MyClass:
    pass

obj = MyClass()
print(obj)

Output

<__main__.MyClass instance at 0x7f1b31f44640> 

Creating a Class with an __init__() Method

Example

In this example, we define a class called `MyClass` with an `__init__()` method. This method is called when we create an instance of the class. It initializes the object's attributes using the values passed in as arguments.

We then create an instance of the class called `obj` and pass in the arguments `1` and `2`. This creates an object with attributes `x=1` and `y=2`.

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(1, 2)
print(obj.x)
print(obj.y)

Output

1
2

Creating a Class with a classmethod()

Example

A class method is a special function that belongs to a class and can be used to create new objects of that class or to modify existing ones. It's like a recipe for creating or changing objects of a certain type.

Suppose we have a class called Animal that has an attribute called species. We can create a class method called make_sound that returns a string representing the sound that an animal of that species makes. For example, a dog might say "Woof woof!" and a cat might say "Meow!".

class Animal:
    def __init__(self, species):
        self.species = species

    @classmethod
    def make_sound(cls, species):
        if species == "dog":
            return "Woof woof!"
        elif species == "cat":
            return "Meow!"
        else:
            return "I don't know what sound that animal makes."

dog = Animal("dog")

print(dog.make_sound("dog"))   
cat = Animal("cat")
print(cat.make_sound("cat"))   
bird = Animal("bird")
print(bird.make_sound("bird")) 

Output

Woof woof!
Meow!
I don't know what sound that animal makes.

Creating a Subclass of an Existing Class

Example 1

In this example, we define a class called `ParentClass`. We then define a subclass of `ParentClass` called `ChildClass` using the syntax `class ChildClass(ParentClass):`. This creates a subclass of `ParentClass` that inherits all of its attributes and methods.

We then create an instance of `ChildClass` called `obj` using parentheses `()` after the class name. This creates an empty object that is an instance of `ChildClass`, which in turn inherits all the attributes and methods of `ParentClass`.

class ParentClass:
    pass

class ChildClass(ParentClass):
    pass

obj = ChildClass()
print(obj)

Output

<__main__.ChildClass object at 0x7fb710464ee0>

Example 2

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

    def introduce(self):
        print(f"My name is {self.name} and I am {self.age} years old.")

# creating an object of Person class
person1 = Person("Alice", 25)

# calling the introduce method of Person class object
person1.introduce()

Output

My name is Alice and I am 25 years old.

In this example, we have defined a Person class with two instance variables name and age and a method introduce which prints the name and age of the person. Then we created an object person1 of the Person class by calling its constructor with arguments "Alice" and 25. Finally, we called the introduce method of the person1 object which prints the name and age of the person.

Example 3

In this example, we have defined a Car class with three instance variables make, model, and year and a method get_info which returns a formatted string containing the year, make, and model of the car. Then we created an object car1 of the Car class by calling its constructor with arguments "Toyota", "Corolla", and 2022. Finally, we called the get_info method of the car1 object which returns a string containing the information about the car and we printed it using the print function.

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def get_info(self):
        return f"{self.year} {self.make} {self.model}"

# creating an object of Car class
car1 = Car("Toyota", "Corolla", 2022)

# calling the get_info method of Car class object
print(car1.get_info())

Output

2022 Toyota Corolla

Updated on: 18-May-2023

598 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements