【问题标题】:Python decorator to add class-level variablesPython 装饰器添加类级变量
【发布时间】:2012-08-14 10:07:43
【问题描述】:

我有 2 个 A 类和 B 类:

class A(object):
    x = 0

class B(object):
    y = 0

我怎样才能通过使用装饰器使 B “继承” A 的类级变量(在本例中为 x) ?有可能吗?期望的行为(如果可能的话),在装饰之后,B 看起来像这样:

class B(object):
    x = 0
    y = 0

注意:如果有人想/需要知道我为什么要问这个问题,这只是为了让 SQLAlchemy 的具体表继承在代码中看起来更好,尽管我可以看到许多此类行为的用例。

【问题讨论】:

    标签: python inheritance metaprogramming decorator python-decorators


    【解决方案1】:

    当然可以;您可以使用将类 A 作为参数的类装饰器,然后为您更新装饰类:

    import types
    
    class copyattributes(object):
        def __init__(self, source):
            self.source = source
    
        def __call__(self, target):
            for attr, value in self.source.__dict__.items():
                if attr.startswith('__'):
                    continue
                if isinstance(value, (property, types.FunctionType)):
                    continue
                setattr(target, attr, value)
            return target
    

    装饰器复制任何真正的属性(不是函数或属性),并且不以双下划线开头。

    用法:

    class A(object):
        x = 0
    
    @copyattributes(A)
    class B(object):
        y = 0
    

    在提示下测试:

    >>> class A(object):
    ...     x = 0
    ...
    >>> @copyattributes(A)
    ... class B(object):
    ...     y = 0
    ... 
    >>> B.y
    0
    >>> B.x
    0
    >>> dir(B)
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x', 'y']
    

    【讨论】:

    • 正是我所需要的,也是一个快速的答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2011-07-25
    • 2012-11-24
    • 2020-10-09
    相关资源
    最近更新 更多