2014-02-23 52 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

相關問題