2014-02-23 53 views
1

我不相信这是可能的,但我想我会问,因为我是新来的Python。给定一个具有属性的对象,其值由描述符处理;是否有可能知道给定的描述符类型是否涉及?是否有可能测试对象属性是否使用描述符?

实施例描述符

class Column(object): 
    def __init__(self, label): 
     self.label = label 

    def __get__(self, obj, owner): 
     return obj.__dict__.get(self.label) 

    def __set__(self, obj, value): 
     obj.__dict__[self.label] = value 

测试对象

class Test(object): 
    name = Column("column_name") 

    def add(self): 
     print self.name.__class__ 

执行此

my_test = Test() 
my_test.name = "myname" 
my_test.add() 

这GIV es:<type 'str'>这是值“myname”的数据类型,是否可以测试isinstance(self.name,Descriptor) - 这将返回false,但我希望它返回true - 或类似的东西?

编辑 - 上Test

+0

是'my_test.name'应该正常被分配给一个列对象? – ForgetfulFellow

+0

不,my_test.name是Test()对象的属性。描述符用于确保名称有效。我使用描述符而不是@property来减少代码,因为它将在很多地方使用。理想情况下,我想知道my_test.name使用列描述符。然而,我不确定这是否可能.. – Matt

+0

@Matt你是否试图确定描述符重写的方法或对象的类是否是描述符? – 2014-02-23 01:26:10

回答

2

旧式类的拆除错误搜索对象在方法解析顺序类和超类的描述符对象:

def find_descriptor(instance, attrname): 
    '''Find the descriptor handling a given attribute, if any. 

    If the attribute named attrname of the given instance is handled by a 
    descriptor, this will return the descriptor object handling the attribute. 
    Otherwise, it will return None. 

    ''' 

    for klass in type(instance).__mro__: 
     if attrname in klass.__dict__: 
      descriptor = klass.__dict__[attrname] 
      if not (hasattr(descriptor, '__get__') or 
        hasattr(descriptor, '__set__') or 
        hasattr(descriptor, '__delete__')): 
       # Attribute isn't a descriptor 
       return None 
      if (attrname in instance.__dict__ and 
       not hasattr(descriptor, '__set__') and 
       not hasattr(descriptor, '__delete__')): 
       # Would be handled by the descriptor, but the descriptor isn't 
       # a data descriptor and the object has a dict entry overriding 
       # it. 
       return None 
      return descriptor 
    return None 
+0

是的,这个作品!它看起来像通过方法解决顺序是我所需要的。我想我只是在阅读价值的课程,而不是通过mro的方式工作。非常感谢! – Matt

相关问题