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 :: instagram login with selenium py 
Python :: How to install XGBoost package in python using conda 
Python :: stack overflow python timedate 
Python :: enumerate python 
Python :: last element in list py 
Python :: how to get location using python 
Python :: await async function from non async python 
Python :: plot histogram python 
Python :: python catch multiple exceptions 
Python :: sqlite3 python parameterized query 
Python :: correlation between two columns pandas 
Python :: google smtp 
Python :: pandas new column from others 
Python :: tkinter keep window in front 
Python :: how to delete a specific line in a file 
Python :: how to use with open 
Python :: python write file 
Python :: how to check django rest framework version 
Python :: multirow np.rand.randint 
Python :: how to write a file in python 
Python :: decision tree classifier 
Python :: convert string to utf8 python 
Python :: python optionmenu tkinter 
Python :: time.perf_counter 
Python :: plotly line plot 
Python :: open file python 
Python :: python ndim 
Python :: fill null values with zero python 
Python :: python detect lines 
Python :: upgrade python wsl 
ADD CONTENT
Topic
Content
Source link
Name
5+8 =