Create custom data type in Python

In this article, we will see how you can create a custom datatype in Python. By using class we can create custom data types in Python. You have to define your own class with required attributes and methods which will represent the characteristics of the custom data types.

Example 1:

In this example, the Person class represents a specific person with age and name attributes. Here in this code, the __str__ method overrides the predefined string representation. The __init__ method initializes the object with the given values name and age.

Code:

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

    def __str__(self):
        return f'Person({self.name})'

Output:

>>> from person import Person
>>> arnab = Person('Arnab Sadhukhan', 24)
>>> print(arnab)
Person(Arnab Sadhukhan)

Example 2:

In this example, Point is a 2D data type that represents a point in a 2-dimensional space. x and are two variables that store two coordinates and distance_to_origin() is a method that calculates the distance between two points.

Code:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def distance_to_origin(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5

# Creating an instance of Point
p1 = Point(3, 4)
print("Coordinates:", p1.x, ",", p1.y)
print("Distance to origin:", p1.distance_to_origin())

Output:

Coordinates: 3 , 4
Distance to origin: 5.0

 

Leave a Reply

Your email address will not be published. Required fields are marked *