【问题标题】:return different results based on what class the parameter is? [duplicate]根据参数是什么类返回不同的结果? [复制]
【发布时间】:2020-11-20 10:49:37
【问题描述】:

编写一个名为depends_on_the_type() 的函数(python3),它接受一个参数obj 是object 的缩写。 该函数适用于数据类型

  • 布尔值,
  • str,
  • 浮动,
  • int

返回的内容取决于对象的数据类型:

  • 如果 obj 是 int:

    • 如果 obj == 0,该函数将返回“零”
    • 如果是偶数,该函数将返回该整数的平方
    • 如果是奇数,该函数将返回该整数的立方
  • 如果obj是浮点数,函数将返回数字乘以1.5

  • 如果 obj 是 str,则函数将返回与自身连接的字符串

  • 如果 obj 是布尔值,则返回该布尔值的否定

  • 如果obj不是上述数据类型之一,返回None

尝试:

def depends_on_the_type(obj):
    if obj == class(int):
        if obj == 0:
            return 'Zero'
        elif obj % 2 == 0:
            return obj**2
        elif obj % 2 == 1:
            return obj**3
    if obj == class(float):
        return obj*1.5
    if obj == class(str):
        return str(obj)
    if obj == class(bool):
        return not bool
    else:
        return None

【问题讨论】:

标签: python function


【解决方案1】:

你应该看看内置函数isinstance()。 它需要两个参数object 和classinfo。 如果 object 参数是 classinfo 参数的实例,则返回 True。 这就是您如何处理obj 是整数的情况。剩下的我想你会自己解决的。

def depends_on_the_type(obj):
    if isinstance(obj, int):
        if obj == 0:
            return 'Zero'
        elif obj % 2 == 0:
            return obj ** 2
        elif obj % 2 == 1:
            return obj ** 3

Here is the documentation for isinstance()

【讨论】:

    【解决方案2】:

    好的,要知道某些数据的类型,您必须使用函数 type(),它接受一个参数并返回值的类型,然后最终它并不总是出现 None 使用“if” ,“elif”,“else”,如果你修改你的代码,它会像这样结束:

    if type(obj) == int :
        if not obj % 2 :
            return "zero"
        elif obj % 2 :
            return obj ** 3
        else:
            return obj ** 2
    elif type(obj) == float:
        return obj ** 1.5
    elif type(obj) == str:
        return obj
    elif type(obj) == bool
        return not bool
    else:
       return None
    
    
    
    
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 2016-08-30
      • 2021-09-03
      • 2016-03-31
      • 2020-08-10
      • 1970-01-01
      • 2018-09-20
      相关资源
      最近更新 更多