我很好奇是否有任何明显的问题,检查python中的变量是否是字典?我意识到它不是非常" pythonic"在python中进行类型检查,但我不确定如何解决我的特定问题。
这是一个例子,我试图根据对象属性是否存在来设置对象的属性,以及b。)是否覆盖了我的覆盖值是一本字典。如果它是字典,则递归函数以设置这些子对象属性。
import six
class OtherObj(object):
def __init__(self, name):
self.name = name
class ExObj(object):
def __init__(self, name, description, other_obj):
self.name = name
self.description = description
self.other_obj = other_obj
def process_dict(obj, **kwargs):
for key, value in six.iteritems(kwargs):
if hasattr(obj, key):
if isinstance(value, dict):
process_dict(getattr(obj, key), **value)
else:
setattr(obj, key, value)
obj = ExObj("my name", "my desc", OtherObj("another name"))
process_dict(obj, **{ "name": "no this is my real name",
"description": "no this is my real desc",
"other_obj": { "name": "other object real name" } })
答案 0 :(得分:4)
嗯,没有明显的问题,但如果你坚持:
[]
访问它,捕捉可能的例外更多Pythonic,但我个人不这么认为。但我正在使用抽象基类:
import collections
isinstance(obj, collections.Mapping)
通过这种方式,该函数可以支持其他可能的映射类型,而不仅仅是dict
。
答案 1 :(得分:0)
在python中进行类型检查实际上非常简单,并且非常有用(至少我认为是这样)。
type(variable)