装饰器只是函数调用的语法糖,因此要将装饰器应用于属性,您只需在初始化程序上调用它:
a = bar(5)
在您的情况下,您可以创建实现描述符协议的对象:
class GroupedAttribute(object):
def __init__(self, group, obj):
self.group = group
self.obj = obj
def __get__(self, obj, owner):
return self.obj
def __set__(self, obj, value):
self.obj = value
为了优雅,您可以为属性组编写一个类:
class GroupedAttribute(object):
def __init__(self, group, obj):
self.group = group
self.obj = obj
def __get__(self, obj, owner):
return self.obj
def __set__(self, obj, value):
self.obj = value
class AttributeGroup(object):
def __call__(self, obj):
return GroupedAttribute(self, obj)
def __get__(self, obj, owner):
return BoundAttributeGroup(self, obj, owner)
class BoundAttributeGroup(object):
def __init__(self, group, obj, owner):
self.group = group
self.obj = obj
self.owner = owner
def __dir__(self):
items = dir(self.owner if self.obj is None else self.obj)
return [item for item in items if
getattr(self.owner.__dict__.get(item, None),
'group', None) is self.group]
用法:
class MyClass(object):
bar = AttributeGroup()
a = bar(5)
b = bar("foo")
c = False
dir(MyClass.bar) # ['a', 'b']