Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

generic type 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 :: pip clear download cache 
Python :: load and image and predict tensorflow 
Python :: current time python 
Python :: python from timestamp to string 
Python :: print % in python 
Python :: python string math 
Python :: python rsa 
Python :: blinking an led with raspberry pi 
Python :: python screen click 
Python :: python set recursion limit 
Python :: python apply function to dictionary values 
Python :: pipilika search engine 
Python :: password text in entry in tkinter 
Python :: python check for folder 
Python :: scapy python import 
Python :: equal sides of an array python 
Python :: pandas iloc select certain columns 
Python :: python how to get current line number 
Python :: np.rand.randint 
Python :: tkinter open new window 
Python :: convert list to string 
Python :: python index list enumerate 
Python :: pyinstaller command 
Python :: remove idx of list python 
Python :: python insert 
Python :: python file handling 
Python :: UTC to ISO 8601: 
Python :: add custom field to serializer 
Python :: np.zeros data type not understood 
Python :: resize interpolation cv2 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =