如何检查给定的member_descriptor对象是否包含引用实例的值

时间:2017-11-15 11:58:21

标签: python-3.x

我正在研究一种与Blender属性定义类似的高级界面。

我正在做的处理数据的方法是用一个在内部保留member_descriptor方法引用的属性覆盖member_descriptor对象。

class Object(object):
    """an example"""
    __slots__ = ['item']
    def __init__(obj):
        obj.item = static_object() # stored in the descriptor and updated

def reassign():
    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val):
        """my problem lies here"""
        if hasattr(Object, 'item'): # this will create an infinite recursion loop
            dscget(obj,Object).update(val)
        elif val.__class__ is static_object: dscset(obj,val)
        else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

    Object.item = property( dscget, setter )

因为hasattr检查属性,检查属性等等,检查描述符是否包含所需项目的更有效和更具效率的方法是什么?

我不想使用try,因为except AttributeError超级慢...... 例如:

    def setter(obj, val):
        """the slow method"""
        try: dscget(obj,Object).update(val)
        except AttributeError: # because the descriptor holds nothing.
            if val.__class__ is static_object: dscset(obj,val)
            else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

是否有另一种方法,或者这是我最好的便便?

2 个答案:

答案 0 :(得分:0)

您可以使用the type function。例如:

if(type(YourObjectInstance) is YourObject)
if(type(5) is int)

答案 1 :(得分:0)

经过一番抨击,并与一位告诉我备份并考虑更好的方法的bpy dev交谈后,我已经确定了这一点:

def reassign():

    class Object(object):
        __slots__ = ['item']
        def __new__(cls):
            obj = object.__new__(cls)
            dscset(obj,static_object())
            return obj
    globals()['Object'] = Object

    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val): dscget(obj,Object).update(val) # leave type checking to the static object
    Object.item = property( dscget, setter )
reassign()
del reassign
# __new__.__closure__ holds the descriptor setter(s)

因此不需要问题中的所有验证BS:D