有没有一种简单的方法来确定变量是列表、字典还是其他什么?
当前回答
通常,您可以从具有类名的对象中提取字符串,
str_class = object.__class__.__name__
并将其用于比较,
if str_class == 'dict':
# blablabla..
elif str_class == 'customclass':
# blebleble..
其他回答
使用类型()
x='hello this is a string'
print(type(x))
输出
<class 'str'>
要仅提取str,请使用
x='this is a string'
print(type(x).__name__)#you can use__name__to find class
输出
str
如果使用类型(变量)__name__我们可以读
可以使用type()或isinstance()。
>>> type([]) is list
True
请注意,通过在当前作用域中分配同名变量,可以删除列表或任何其他类型。
>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'
上面我们看到dict被重新分配给一个字符串,因此测试:
type({}) is dict
…失败。
要解决此问题并更谨慎地使用type():
>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True
使用类型():
>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>
在许多实际情况下,您也可以使用@functools.singledispatch来定义泛型函数(由多个函数组成的函数,对不同类型执行相同的操作),而不是使用类型或isinstance。
换句话说,当您有如下代码时,您可能希望使用它:
def do_something(arg):
if isinstance(arg, int):
... # some code specific to processing integers
if isinstance(arg, str):
... # some code specific to processing strings
if isinstance(arg, list):
... # some code specific to processing lists
... # etc
下面是一个工作原理的小示例:
from functools import singledispatch
@singledispatch
def say_type(arg):
raise NotImplementedError(f"I don't work with {type(arg)}")
@say_type.register
def _(arg: int):
print(f"{arg} is an integer")
@say_type.register
def _(arg: bool):
print(f"{arg} is a boolean")
>>> say_type(0)
0 is an integer
>>> say_type(False)
False is a boolean
>>> say_type(dict())
# long error traceback ending with:
NotImplementedError: I don't work with <class 'dict'>
此外,我们可以使用抽象类同时覆盖几种类型:
from collections.abc import Sequence
@say_type.register
def _(arg: Sequence):
print(f"{arg} is a sequence!")
>>> say_type([0, 1, 2])
[0, 1, 2] is a sequence!
>>> say_type((1, 2, 3))
(1, 2, 3) is a sequence!
type()是比isinstance()更好的解决方案,尤其是对于布尔值:
True和False只是python中表示1和0的关键字。因此
isinstance(True, int)
and
isinstance(False, int)
两者都返回True。两个布尔值都是整数的实例。然而,type()更聪明:
type(True) == int
返回False。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象