裝飾只是SY函數調用ntactic糖,這樣的裝飾應用到屬性,你只需要調用它的初始化器:
在你的情況,你可以創建實現描述符協議對象:
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']
我會說#2是要走的路。這是迄今爲止最簡單,最簡單的方法。 – delnan
所以我忘了寫 - 我想從這個列表中獲得一些想法;) – mnowotka
您的意思是「保持這個分組屬性接近屬性」是什麼意思?您是否指代字典的鍵值存儲屬性? – abought