Mat*_*son 7 python descriptor python-datamodel
我已经开始在我编写的代码中更广泛地使用python描述符协议.通常,默认的python查找魔法是我想要发生的,但有时我发现我想获取描述符对象本身而不是其__get__方法的结果.想知道描述符的类型,或者描述符中存储的访问状态,或者某些东西.
我编写了下面的代码,以我认为正确的顺序遍历名称空间,并返回属性raw,无论它是否是描述符.我很惊讶,虽然我无法在标准库中找到内置函数或其他内容来实现这一点 - 我认为它必须在那里,我只是没有注意到它或用Google搜索正确的搜索词.
python发行版中的某个地方是否有功能(或类似的东西)?
谢谢!
from inspect import isdatadescriptor
def namespaces(obj):
obj_dict = None
if hasattr(obj, '__dict__'):
obj_dict = object.__getattribute__(obj, '__dict__')
obj_class = type(obj)
return obj_dict, [t.__dict__ for t in obj_class.__mro__]
def getattr_raw(obj, name):
# get an attribute in the same resolution order one would normally,
# but do not call __get__ on the attribute even if it has one
obj_dict, class_dicts = namespaces(obj)
# look for a data descriptor in class hierarchy; it takes priority over
# the obj's dict if it exists
for d in class_dicts:
if name in d and isdatadescriptor(d[name]):
return d[name]
# look for the attribute in the object's dictionary
if obj_dict and name in obj_dict:
return obj_dict[name]
# look for the attribute anywhere in the class hierarchy
for d in class_dicts:
if name in d:
return d[name]
raise AttributeError
Run Code Online (Sandbox Code Playgroud)
编辑星期三,2009年10月28日.
Denis的回答给了我一个在我的描述符类中使用的约定来获取描述符对象本身.但是,我有一个描述符类的完整类层次结构,我不想用样板开始每个 __get__函数
def __get__(self, instance, instance_type):
if instance is None:
return self
...
Run Code Online (Sandbox Code Playgroud)
为了避免这种情况,我使描述符类树的根继承自以下内容:
def decorate_get(original_get):
def decorated_get(self, instance, instance_type):
if instance is None:
return self
return original_get(self, instance, instance_type)
return decorated_get
class InstanceOnlyDescriptor(object):
"""All __get__ functions are automatically wrapped with a decorator which
causes them to only be applied to instances. If __get__ is called on a
class, the decorator returns the descriptor itself, and the decorated
__get__ is not called.
"""
class __metaclass__(type):
def __new__(cls, name, bases, attrs):
if '__get__' in attrs:
attrs['__get__'] = decorate_get(attrs['__get__'])
return type.__new__(cls, name, bases, attrs)
Run Code Online (Sandbox Code Playgroud)
Den*_*ach 13
大多数描述符仅在作为实例属性访问时才起作用.因此,在课程访问时返回自己很方便:
class FixedValueProperty(object):
def __init__(self, value):
self.value = value
def __get__(self, inst, cls):
if inst is None:
return self
return self.value
Run Code Online (Sandbox Code Playgroud)
这允许您获取描述符本身:
>>> class C(object):
... prop = FixedValueProperty('abc')
...
>>> o = C()
>>> o.prop
'abc'
>>> C.prop
<__main__.FixedValueProperty object at 0xb7eb290c>
>>> C.prop.value
'abc'
>>> type(o).prop.value
'abc'
Run Code Online (Sandbox Code Playgroud)
请注意,这也适用于(大多数?)内置描述符:
>>> class C(object):
... @property
... def prop(self):
... return 'abc'
...
>>> C.prop
<property object at 0xb7eb0b6c>
>>> C.prop.fget
<function prop at 0xb7ea36f4>
Run Code Online (Sandbox Code Playgroud)
当您需要在子类中扩展它时,访问描述符可能很有用,但有更好的方法来执行此操作.