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 :: break line in string python 
Python :: dictionary python values 
Python :: django choicefield empty label 
Python :: jupyterlab interactive plot 
Python :: python sort a 2d array by custom function 
Python :: print out session information django 
Python :: compare multiple columns in pandas 
Python :: exponent in python 
Python :: with open 
Python :: how to find unique values in numpy array 
Python :: plotly coordinates mapping 
Python :: plot scatter and line together 
Python :: move column in pandas dataframe 
Python :: python dict del key 
Python :: django override delete 
Python :: download unsplash images script 
Python :: read api from django 
Python :: how to read first column of csv intro a list python 
Python :: run all python files in a directory in windows 
Python :: find array length in python 
Python :: latest version of python 
Python :: continue python 
Python :: sort dict 
Python :: Kivy FileChooser 
Python :: how to hide tkinter window 
Python :: boxplot python 
Python :: python tkinter checkbox default value 
Python :: How to filter with Regex in Django ORM 
Python :: import module python same directory 
Python :: how to remove a list of numbers from a list in python 
ADD CONTENT
Topic
Content
Source link
Name
5+8 =