Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

generics python

# Generics can be parameterized by using a factory available in typing called TypeVar.
from collections.abc import Sequence
from typing import TypeVar

T = TypeVar('T')      # Declare type variable

def first(l: Sequence[T]) -> T:   # Generic function
    return l[0]
Comment

python generic

# Python method overloading in a class
from functools import singledispatchmethod, singledispatch
class Foo:
    @singledispatchmethod
    def add(self, *args):
        res = 0
        for x in args:
            res += x
        print(res)
        
    @add.register(str)
    def _(self, *args):
        string = ' '.join(args)
        print(string)
        
    @add.register(list)
    def _(self, *args):
        myList = []
        for x in args:
            myList += x
        print(myList)

obj = Foo()
obj.add(1, 2, 3)        			# 6
obj.add('I', 'love', 'Python')      # I love Python
obj.add([1, 2], [3, 4], [5, 6])     # [1, 2, 3, 4, 5, 6]

# for independent methods
from datetime import date, time

@singledispatch
def format(arg):
    print(arg)

@format.register            # syntax version 1
def _(arg: date):
    print(f"{arg.day}-{arg.month}-{arg.year}")

@format.register(time)      # syntax version 2
def _(arg):
    print(f"{arg.hour}:{arg.minute}:{arg.second}")

format("today")                      # today
format(date(2021, 5, 26))            # 26-5-2021
format(time(19, 22, 15))             # 19:22:15
Comment

PREVIOUS NEXT
Code Example
Python :: python - oordinated universal time 
Python :: How to install XGBoost package in python 
Python :: convert pandas column type 
Python :: matplotlib plot 2d point 
Python :: python version installed in ubuntu 
Python :: how to make images in python 
Python :: Column names reading csv file python 
Python :: pandas string to number 
Python :: modulus of python complex number 
Python :: how to run django tests 
Python :: flask get ip of user 
Python :: python largest value in list 
Python :: python remove form list 
Python :: split a given number in python 
Python :: merge two df 
Python :: python3 yyyymmddhhmmss 
Python :: replace values of pandas column 
Python :: OneHotEncoder(categorical_features= 
Python :: create 3x3 numpy array 
Python :: how to create a countdown timer using python 
Python :: django change user password 
Python :: rename key in dict python 
Python :: how to add element at first position in array python 
Python :: register model in admin django 
Python :: check python version kali linux 
Python :: python open file 
Python :: read json file python 
Python :: spacy nlp load 
Python :: python get volume free space 
Python :: unzip_data python 
ADD CONTENT
Topic
Content
Source link
Name
7+3 =