我不相信这是可能的,但我想我会问,因为我是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()
这给出:<type 'str'>
这是值“myname”的数据类型,是否可以测试isinstance(self.name,Descriptor) - 这会返回false,但我希望它返回true - 或类似的东西?
修改 - 删除Test
上旧式课程的错误
答案 0 :(得分: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