简体   繁体   中英

use same function for different types

I have following function:

def calculate_digits(number: Union[int, float, str]) -> int:
    absolute_value: float = abs(number)
    rounded_value: int = math.floor(absolute_value)
    total_digits_needed: int = calculate_length_integer(rounded_value)
    return total_digits_needed

As you can see, I want to use this for different python types: int, float, str... As the abs() only works for floats I was wondering, how do I deal best with this? Do I need to write a function with if, elsif statement to do this, or is there a better way to do this?

For me abs() works on int too... I'm using python 3.9.

For example the code below works for me at least:

number = abs(3)

Check if you need to update

First, abs doesn't just work for float s; it works for numbers . At the very least:

  • int
  • float
  • complex
  • decimal.Decimal

There may be others. You might even be able to use numbers.Number as the type hint, though I'm not sure if that might not be too broad.

Second, this function really should be two functions, as a string is quite different from a numeric type.

def calculate_digits(number: Union[int, float]) -> int:
    absolute_value = abs(number)
    rounded_value = math.floor(absolute_value)
    return cacalculate_length_integer(rounded_value)

def calculate_digits_from_string(n: str) -> int:
    x = ... # Convert the string to an appropriate number.
    # There isn't enough detail in the question to know
    # which strings can be appropriate converted; float(n)
    # might be sufficient, though it could fail for an arbitrary
    # string.
    return calculate_digts(x)

You could combine them again, but I wouldn't recommend it, as the work to convert a string to a number should be kept separate.

def calculate_digits(number: Union[int, float, str]) -> int:
    if isinstance(number, str):
        number = ...  # Convert as above
    absolute_value = abs(number)
    rounded_value = math.floor(absolute_value)
    return cacalculate_length_integer(rounded_value)

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