Python装饰器添加类级变量 - python

我有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的Concrete Table Inheritance在代码中看起来更好,尽管我可以看到很多这种情况的用例。

python大神给出的解决方案

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

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python:同时在for循环中添加到列表列表 - python

我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…

re.findall不返回全场比赛吗? - python

我有一个包含一堆字符串的文件,例如“ size = XXX;”。我第一次尝试使用python的re模块,并且对以下行为感到有些困惑:如果我在正则表达式中使用管道作为“或”,我只会看到返回的匹配项。例如。:>>> myfile = open('testfile.txt','r').read() >…

Spacy如何将标记标签整体化? - python

在包含#标签(例如tweet)的句子中,spacy的令牌生成器将标签分为两个令牌:import spacy nlp = spacy.load('en') doc = nlp(u'This is a #sentence.') [t for t in doc] 输出:[This, is, a, #, sentence, .…