简体   繁体   English

如何判断python变量中包含哪种类型的数据?

[英]How do I tell what type of data is inside python variable?

I have a list of variables.. inside the list are strings, numbers, and class objects. 我有一个变量列表..列表中是字符串,数字和类对象。 I need to perform logic based on each different type of data. 我需要根据每种不同类型的数据执行逻辑。 I am having trouble detecting class objects and branching my logic at that point. 我在检测类对象和分支逻辑时遇到了麻烦。

if(type(lists[listname][0]).__name__ == 'str'): # <--- this works for strings
elif(type(lists[listname][0]).__name__ == 'object'): <--- this does not work for classes

in the second line of code above, the name variable contains "Address" as the class name. 在上面的第二行代码中, name变量包含“ Address”作为类名。 I was hoping it would contain "class" or "object" so I could branch my program. 我希望它包含“类”或“对象”,以便可以分支程序。 I will have many different types of objects in the future, so it's a bit impractical to perform logic on every different class name, "Address" "Person" etc 将来我将有许多不同类型的对象,因此对每个不同的类名,“地址”,“人”等执行逻辑有点不切实际。

please let me know if my question needs clarification. 如果我的问题需要澄清,请告诉我。

thanks!! 谢谢!!

FYI: it also makes a difference if its a new-style class or not: 仅供参考:无论是否使用新型类,这也都有所不同:

# python
type(1).__name__
'int'
type('1').__name__
'str'
class foo(object):
  pass
type(foo()).__name__
'foo'
class bar:
  pass
type(bar()).__name__
'instance'

If you can make sure they're all new-style classes, your method will determine the real type. 如果可以确保它们都是新式类,则您的方法将确定实际类型。 If you make them old-style, it'll show up as 'instance'. 如果您将它们设为旧样式,它将显示为“实例”。 Not that I'm recommending making everything all old-style just for this. 并不是说我建议为此而将所有内容都变为旧样式。

However, you can take it one step further: 但是,您可以更进一步:

type(bar().__class__).__name__
'classobj'
type(foo().__class__).__name__
'type'

And always look for 'classobj' or 'type'. 并始终寻找“ classobj”或“ type”。 (Or the name of the metaclass, if it has one.) (或元类的名称,如果有的话。)

I think you want the isinstance function. 我认为您需要isinstance函数。

if isinstance(o, ClassName):

However, you'll need to first verify that o is an object, you can use type for that. 但是,您需要首先验证o是一个对象,可以为此使用type

It's common in Python to use exception handling to decide which code path to take; 在Python中,使用异常处理来决定采用哪个代码路径是很常见的。 inspecting the exact type of an object (with isinstance()) to decide what to do with it is discouraged. 不建议检查对象的确切类型(使用isinstance())以决定如何处理该对象。

For example, say that what you want to do is, if it's a string, print it in "title case", and if it's an object, you want to call a particular method on it. 例如,假设您要执行的操作是,如果它是字符串,则以“标题大小写”方式打印,如果它是对象,则要在其上调用特定的方法。 So: 所以:

try:
    # is it an object with a particular method?
    lists[listname][0].particularMethod()
except AttributeError:
    # no, it doesn't have particularMethod(), 
    # so we expect it to be a string; print it in title case
    print lists[listname][0].title()

If you are only interested in handling two types specifically, you could test for them explicitly using isinstance and then handle the leftovers: 如果您只对专门处理两种类型感兴趣,则可以使用isinstance显式测试它们,然后处理剩余的:

import numbers

for item in list:
    if isinstance(item, basestring): # (str, unicode)
        do_string_thing(item)
    elif isinstance(item, numbers.Real): # (int, float, long)
        do_number_thing(item)
    else:
        do_object_thing(item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何告诉python我的数据结构(二进制)是什么样子,以便我可以绘制它? - How do I tell python what my data structure (that is in binary) looks like so I can plot it? 我如何知道在Python中使用哪种数据类型? - How do I know what data type to use in Python? 如何判断脚本需要哪个版本的 Python? - How do I tell what version of Python a script needs? 如何告诉Python IDE(和解释器)变量的类型 - How to tell the Python IDE (and interpreter) the type of a variable python,如何判断返回的是哪种类型的obj - python, how to tell what type of obj was returned 我在 python 中打开文本后的数据类型是什么,如何获取 txt 中的单词? - What is the data type after i open a text in python and how can i get the word inside the txt? 我如何知道我已成功用Python导入了哪些库以及这些库为我提供了什么功能? - How do I tell what libraries I have succesfully imported in Python and what functions these libraries offer me? 如何告诉Pig什么是PyObject? - How do I tell Pig what a PyObject is? 如何告诉 python 传递给 function 的意外变量类型在上下文中是正确的 - How to tell python that the unexpected variable type passing to a function is correct in the context 我如何告诉 PyCharm 用户定义的 function 字典中的 python 类型是可以的? - How do I tell PyCharm user defined type of python dict in a function is okay?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM