Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
添加类级变量的Python装饰器_Python_Inheritance_Metaprogramming_Decorator_Python Decorators - Fatal编程技术网

添加类级变量的Python装饰器

添加类级变量的Python装饰器,python,inheritance,metaprogramming,decorator,python-decorators,Python,Inheritance,Metaprogramming,Decorator,Python Decorators,我有两个班级A和B: class A(object): x = 0 class B(object): y = 0 如何通过使用decorator使B继承A的类级变量(x)?有可能吗?装饰后,B所需的行为(如果可能)如下所示: class B(object): x = 0 y = 0 注意:如果有人想/需要知道我为什么要问这个问题,那只是为了让SQLAlchemy的具体表继承在代码中看起来更好,尽管我可以看到很多这种行为的用例。当然可以;您可以使用以类a为参

我有两个班级A和B:

class A(object):
    x = 0

class B(object):
    y = 0
如何通过使用decorator使B继承A的类级变量(x)?有可能吗?装饰后,B所需的行为(如果可能)如下所示:

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


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

当然可以;您可以使用以类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']

正是我需要的,还有一个快速的回答!