【发布时间】:2013-08-19 20:05:50
【问题描述】:
我有一个 django 模型,需要参考自定义用户模型进行一些处理。
由于类的加载顺序未知,我无法在类加载时使用此模型的类。
所以我需要在运行时添加一些类属性,目前我正在将它们添加到__init__ 或__new__ 中,例如:
def __new__(cls, *args, **kwargs):
# hack to avoid INSTALLED_APPS initialization conflicts.
# get_user_model() can't be called from this module at class loading time,
# so some class attributes must be added later.
# Metaclasses could me more appropiate but I don't want to override
# dango's metaclasses.
if not hasattr(cls, '_reverse_field_name_to_user'):
cls._find_reverse_field_name_to_user()
return Group.__new__(cls, *args, **kwargs)
它可以工作,但看起来很糟糕,所以我考虑过为这些属性使用类似 @lazyclassproperty 的东西。
我找到了几个 @classproperty 和 @lazyproperty 装饰器,但没有一个适合两者,我不知道如何自己编写一个。
问题:我如何编写这样的装饰器?或者建议我目前愚蠢的实施的另一种更清洁的替代方案。
【问题讨论】:
标签: python django decorator lazy-evaluation class-attributes