简单树代码
class A_1:
    saveable =True
    
class A_2:
    saveable =False
    
class B_1:
    saveable =True
    
class B_2:
    saveable =False
    
class C_1:
    saveable =False
    
class C_2:
    saveable =True
    
class A:
    saveable = True
    inline = [A_1,A_2]
class B:
    saveable = False
    inline = [B_1,B_2]
class C:
    saveable = True
    inline = [C_1,C_2]
class Main:
    inline =[A,B,C]代码图是:

我想要一个函数或方法来根据保存属性对节点进行排序。我想要的输出如下:
>>Main.inline
[B, C, A]
>>A.inline
[A_2,A_1]诸若此类
如果我们绘制的输出是相同的,如下所示:

发布于 2021-01-05 15:23:29
虽然我不同意的方法,但这是您需要做的:(我尽可能少地修改了代码,并在底部添加了测试以证明它有效)
import operator
class A_1:
    saveable =True
class A_2:
    saveable =False
class B_1:
    saveable =True
class B_2:
    saveable =False
class C_1:
    saveable =False
class C_2:
    saveable =True
class Ordered(type):
    def __new__(cls, name, bases, attr):
        new_klass = super(Ordered, cls).__new__(cls, name, bases, attr)
        # Uncomment the line bellow after you've read the comment in all the 
        # way at the bottom of the code.
        #
        # new_klass.inline.sort(key=lambda x: x.__name__, reverse=True)
        new_klass.inline.sort(key=operator.attrgetter('saveable'))
        return new_klass
class A(metaclass=Ordered):
    saveable = True
    inline = [A_1,A_2]
class B(metaclass=Ordered):
    saveable = False
    inline = [B_1,B_2]
class C(metaclass=Ordered):
    saveable = True
    inline = [C_1,C_2]
class Main(metaclass=Ordered):
    inline =[A,B,C]
# this differs from your example slightly, since you asked 
# for `[B, C, A]`, in order to get that working, is just a 
# matter of changing the `sort()` above, and uncommenting 
# the commented line in the function. I left it there in
# case you REALLY wanted it. I figured this would be enough
# and the alternative just complicates things further
assert Main.inline == [B, A, C]
# assert Main.inline == [B, C, A]
assert A.inline == [A_2, A_1]https://stackoverflow.com/questions/65564879
复制相似问题