Python:类属性,默认为parent';s值,并可为整个层次结构收集

Python:类属性,默认为parent';s值,并可为整个层次结构收集,python,metaclass,class-attributes,Python,Metaclass,Class Attributes,这个问题很难用语言表达。我希望标题能正确地抓住它 我要找的是: class Parent(): x = "P" class ChildA(Parent): x = "A" class ChildB(Parent): # not setting x pass 在这种情况下,以下各项应完全如图所示: >>> Parent.x 'P' >>> ChildA.x 'A' >>> ChildB.x 'P' >

这个问题很难用语言表达。我希望标题能正确地抓住它

我要找的是:

class Parent():
    x = "P"

class ChildA(Parent):
    x = "A"

class ChildB(Parent):
    # not setting x
    pass
在这种情况下,以下各项应完全如图所示:

>>> Parent.x
'P'
>>> ChildA.x
'A'
>>> ChildB.x
'P'
>>> ChildB.x = 'B'
>>> ChildB.x
'B'
到目前为止还没有什么特别之处,但这里是比较棘手的地方,因为应该保留父属性的值:

>>> ChildB.x = None
>>> ChildB.x
'P'
另外,我需要这个来工作:

>>> ChildA.get_x_list()
['A', 'P']
>>> ChildB.get_x_list()
['P'] # 'P' only appears once
我最近读了很多关于元类的书,我认为最好使用元类:

has__attr = lambda obj, name: hasattr(obj, "_" + obj.__name__ + "__" + name)
get__attr = lambda obj, name: getattr(obj, "_" + obj.__name__ + "__" + name)
set__attr = lambda obj, name, value: setattr(obj, "_" + obj.__name__ + "__" + name, value)
del__attr = lambda obj, name: delattr(obj, "_" + obj.__name__ + "__" + name)

class Meta(type):
    the_parent_name = "mParent"

    def __new__(cls, class_name, bases, attributes):
        parent_attribute_id = "_" + class_name + "__" + cls.the_parent_name

        x = attributes.pop("x", None)
        if x:
            attributes["_" + class_name + "__x"] = x

        # build line of inheritance
        for b in bases:
            # find a base that has the parent attribute
            if has__attr(b, cls.the_parent_name):
                # set the parent attribute on this class
                attributes[parent_attribute_id] = b
                break
        else:
            # add the parent attribute to this class, making it an inheritance root
            attributes[parent_attribute_id] = None
        return super(Meta, cls).__new__(cls, class_name, bases, attributes)

    def get_x_list(self):
        ls = [get__attr(self, "x")] if has__attr(self, "x") else []
        parent = get__attr(self, self.the_parent_name)
        if parent:
            ls.extend(parent.get_x_list())
        return ls

    @property    
    def x(self):
        if has__attr(self, "x"):
            return get__attr(self, "x")
        else:
            parent = get__attr(self, self.the_parent_name)
            if parent:
                return parent.x
            else:
                return None

    @x.setter
    def x(self, x):
        if x:
            set__attr(self, "x", x)
        else:
            del__attr(self, "x")
虽然这已经完全按照预期工作了,但我想知道是否使用元类是过分的,事实上有一种更简单的方法来做到这一点

重要提示:我需要以一种绝对不会在派生类中执行特殊操作的方式来完成此操作
x=“Q”
set\x(“Q”)
是可以接受的。这是一个要求,因为我正在设计一个API,其中
Parent
是库的一部分,派生类不在我的掌握之中

附加问题:有没有一种方法可以使属性的名称(“x”)在一个位置上改变?含义:是否可以通过字符串创建
get_x_list
x
属性?我想象着这样的事情:

attributes["get_" + attr_name + "_list"] = ...
但每当我尝试时,我得到:

... missing 1 required positional argument: 'self'

这两种功能都不需要元类

>>> ChildB.x = None
>>> ChildB.x
'P'
只需将第一行更改为
del ChildB.x
,就可以了

>>> ChildA.get_x_list()
['A', 'P']
>>> ChildB.get_x_list()
['P'] # 'P' only appears once
试试这个:

(klass.__dict__['x'] for klass in ChildA.__mro__ if 'x' in klass.__dict__)

如果需要列表而不是生成器,请将最外面的一对括号改为方括号。

@SheridanVespo:它应该怎么做?如果它引发了一个
AttributeError
,则您违反了,返回
None
可能也有同样的问题。我以前在控制台中尝试过它,但它不起作用。我刚才试的时候,成功了。我不知道我做错了什么。请原谅我已经删除的评论,你是对的。