【问题标题】:Python: more elegant way to assert type of function inputPython:更优雅的断言函数输入类型的方法
【发布时间】:2021-02-20 13:19:07
【问题描述】:

我是 Python 的初学者...目前我正在尝试编写一个函数,它首先检查输入 x 和 y 是 int 还是 float。

我猜这个工作是什么

if (type(x) != int and type(x) != float) or (type(y) != int and type(y) != float):

但是,这对我来说似乎很笨拙/效率低下,并且在有很多输入的情况下很难概括。因此我认为应该有一种更优雅的方式来编写这个条件..?感谢您的任何想法!

【问题讨论】:

  • 使用isinstance()
  • 非常感谢您的回答,isinstance() 函数正是我想要的!

标签: python function if-statement types


【解决方案1】:

使用isinstance:

if not isinstance(x, (int, float)) and not isinstance(y, (int, float)):
    # do something..

【讨论】:

    【解决方案2】:

    使用isinstance

    if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
    

    【讨论】:

      【解决方案3】:

      使用isinstance - 请参阅下面的代码示例

      https://www.programiz.com/python-programming/methods/built-in/isinstance

      def foo(x, y):
          if isinstance(x, (int, float)) and isinstance(y, (int, float)):
              print('great input')
          else:
              print('wrong input')
      

      【讨论】:

        【解决方案4】:

        可能最通用的方法是使用来自numbers 模块的基类:

        from numbers import Number
        
        if isinstance(3.3, Number):
            ...
        

        小警告:这也将接受复数(例如2 + 4j)。如果你想避免这种情况:

        from numbers import Real, Integral
        
        if isinstance(3.3, (Real, Integral)):
            ...
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-27
          • 2021-06-15
          相关资源
          最近更新 更多