Create light weight object in python and Named Tuple Examples

Create light weight object

 

What is an object in an object-oriented programming language (python)

An object is a thing that has a value named 'properties' and acts named 'behavior'. It can be said that an object is the combination of some properties and behavior in terms of things. In Python, everything is an object with properties and functions. A Class functions similarly to an object constructor or a "blueprint" for constructing things. 


The traditional way to create an object in the python language

person object

The traditional way to create an object in python OOP language (Object-oriented language) is to define some properties by the 'class' keyword and then make a blueprint of that things. There is an example below which is defined to make an object named 'Person'.

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

What are 'Named Tuples'

By the name of 'Named Tuples', we can understand that this is a tuple like other tuples defined in python language. A NamedTuple is a tuple that is used to create a normal lightweight, easily readable, and self-documented object. 

Uses of Named Tuples

Named Tuples can be used in any place where normal tuples are used, and they provide the ability to access fields by name rather than positional indexing of tuples parameters. 

Drawbacks of 'Named Tuples'

One of the reasons should be mentioned that the creation of lightweight objects using Named Tuple in python is not as strong as the traditional way to create a python object. You can't initialize the constructor or manage more constructor that is created using the Named Tuple package.

Named Tuple Examples

person object


The same example of the object 'Person' creation using python language is defined below for the 'Named Tuples' function.

#Method 1

#creating a light weight object in python ( type tuple )
from collections import namedtuple
Person = namedtuple('Person', ['name', 'height', 'weight', 'age'
])


#Method 2

#creating a light weight object in python ( type docstring )
from typing import NamedTuple
class ANamedTuple(NamedTuple):
name: str
height: int
weight: int
age:
int

Application of Named Tuples

The application of named tuples has been discussed and applied to solve a line algorithm in this post 'How to draw a line in python?'.


Post a Comment

Previous Post Next Post