【问题标题】:type() input, print based on data type()type() 输入,根据数据 type() 打印
【发布时间】:2017-08-09 15:54:19
【问题描述】:

编写一个函数 data_type ,它接受一个参数并打印出该参数的数据类型。所以如果我们给一个字符串作为输入,它会说我们的输入是一个字符串,如果我们给一个整数或一个浮点数也是一样的。 如果有人能给我一些解释,我不知道我做错了什么,我将非常感激!希望我对这个问题很清楚。

def data_type(x,y):
    for i in x,y:
        if i == type(str):
            print "str"
        elif i == type(int):
            print "int"
        else:
            if i == type(float):
                print "float"

data_type(1,"string")

【问题讨论】:

  • 你说反了,应该是type(i) == int,而不是i == type(int)...
  • 该函数应采用 one 参数。启动 Python 并输入 type(0)type([])type("hello")。观察结果。 (你不能枚举所有可能存在的类型,所以一堆条件不会有什么好处。)
  • 听起来你只想要函数type...
  • 谢谢你们,现在我明白我的错误在哪里了,有点愚蠢但我最近开始编程......
  • @molbdnilo 如果你有时间,你介意展示你的方法吗

标签: python python-2.7 types


【解决方案1】:

一个更简单的函数实现:

def print_types(*args):
    for arg in args:
        print(type(arg).__name__)

对此的一些说明:

*args 语法允许函数接受许多位置参数,它们将被“打包”到 args 中(作为元组可供函数使用)。 type(x) 将返回 x 的类型,它具有 __name__ 属性。

请注意,对于“旧式”类(在 python2 中,那些不继承自 object 的类),这有点不正确,您需要对此进行调整:

>>> class C: pass
... 
>>> type(C())
<type 'instance'>
>>> type(C()).__name__
# Not what we want
'instance'

如果您还想处理旧式对象:

def print_types(*args):
    for arg in args:
        try:
            print(arg.__class__.__name__)
        except AttributeError:
            print(type(arg).__name__)

快速演示

>>> class C: pass
... 
>>> class D(object): pass
... 
>>> print_types(C, C(), D, D(), 'foo', 2)
classobj
C
type
D
str
int

在没有“旧样式类”概念的 python3 中,您将获得以下内容:

>>> print_types(C, C(), D, D(), 'foo', 2)
type
C
type
D
str
int

【讨论】:

  • 非常感谢您的时间和精力,我理解您的概念,但是现在我不允许使用课程,因为我还没有在我的大学讲座中涵盖它们,我将处理1个月后与他们一起。这肯定会在未来有所帮助!
【解决方案2】:

你想得太通俗了。 i == type(str) 模糊地读起来像“我是字符串类型”,但实际上并不意味着。

您可以通过将type(str) 输入您的解释器来了解它是什么。它会告诉你strtype 类型,这是有道理的,因为str 是一个类型。

例如,"hello" == type(str)"hello" == type 相同。这毫无意义——字符串“hello”显然与type 的概念不同,因此它的计算结果为False

你真正想问的是“hello”的type是否和str的类型是一样的。您可以检查如下:type(i) == str。对您的其余代码进行类似调整即可使其正常工作。

【讨论】:

  • 感谢您的努力,先生!
猜你喜欢
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 2013-07-20
  • 1970-01-01
相关资源
最近更新 更多