简体   繁体   中英

How to turn arguments into floats

I just started learning python and would like to know if there was a way to turn my arguments into a float another way than how I'm doing it. A more simple way instead of turning them into a variable first.

def add(arg1, arg2):
  a = float(arg1)
  b = float(arg2)
  return a + b

I would use a decorator for such thing

from functools import wraps
def floatArgs(f):
    @wraps(f)
    def wrapper(*args):
        return f(*map(float, args))
    return wrapper

@floatArgs
def add(arg1, arg2):
  return arg1 + arg2


>>> add(4,5)
9.0

One generic aproach could be use a generic decorator for mapping types over arguments using an argument itself:

def typeArgs(t):
    def retF(f):
        @wraps(f)
        def wrapper(*args):
            return f(*map(t, args))
        return wrapper
    return retF

@typeArgs(float)
def add(arg1, arg2):
  return arg1 + arg2

@typeArgs(str)
def concatenate(arg1, arg2):
    return arg1 + arg2

>>> add(4, 5)
9.0

>>> concatenate(4,5)
'45'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM