如何检查对象是否是新式用户定义类的实例? [英] How to check if object is instance of new-style user-defined class?

查看:52
本文介绍了如何检查对象是否是新式用户定义类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

导入类型C类(对象):经过c = C()打印(isinstance(c,types.InstanceType))

输出:

检查对象是否是新样式类的用户定义类的实例的正确方法是什么?

更新:

我想进一步强调是否检查对象类型是否用户定义.根据文档:

<块引用>

types.InstanceType
用户定义类的实例类型.

UPD2:

好吧 - 不是正确"的方法也可以.

UPD3:

还注意到模块types

中没有set的类型

解决方案

您可以将 x.__class__ 检查与 dir(x) 或 hasattr(x, '__slots__'),作为一种区分新/旧样式类和用户/内置对象的黑客方法.

实际上,这个完全相同的建议出现在 https://stackoverflow.com/a/2654806/1832154>

def is_instance_userdefined_and_newclass(inst):cls = inst.__class__如果 hasattr(cls, '__class__'):return ('__dict__' in dir(cls) 或 hasattr(cls, '__slots__'))返回错误

<小时><预><代码>>>>A类:通过...>>>B类(对象):通过...>>>a = A()>>>b = B()>>>is_instance_userdefined_and_newclass(1)错误的>>>is_instance_userdefined_and_newclass(a)错误的>>>is_instance_userdefined_and_newclass(b)真的

Code:

import types


class C(object):
    pass


c = C()
print(isinstance(c, types.InstanceType))

Output:

False

What correct way to check if object is instance of user-defined class for new-style classes?

UPD:

I want put additional emphasize on if checking if type of object is user-defined. According to docs:

types.InstanceType
The type of instances of user-defined classes.

UPD2:

Alright - not "correct" ways are OK too.

UPD3:

Also noticed that there is no type for set in module types

解决方案

You can combine the x.__class__ check with the presence (or not) of either '__dict__' in dir(x) or hasattr(x, '__slots__'), as a hacky way to distinguish between both new/old-style class and user/builtin object.

Actually, this exact same suggestions appears in https://stackoverflow.com/a/2654806/1832154

def is_instance_userdefined_and_newclass(inst):
    cls = inst.__class__
    if hasattr(cls, '__class__'):
        return ('__dict__' in dir(cls) or hasattr(cls, '__slots__'))
    return False


>>> class A: pass
... 
>>> class B(object): pass
... 
>>> a = A()
>>> b = B()
>>> is_instance_userdefined_and_newclass(1)
False
>>> is_instance_userdefined_and_newclass(a)
False
>>> is_instance_userdefined_and_newclass(b)
True

这篇关于如何检查对象是否是新式用户定义类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆