The code of simple tree
JavaScript
x
33
33
1
class A_1:
2
saveable =True
3
4
class A_2:
5
saveable =False
6
7
class B_1:
8
saveable =True
9
10
class B_2:
11
saveable =False
12
13
class C_1:
14
saveable =False
15
16
class C_2:
17
saveable =True
18
19
20
class A:
21
saveable = True
22
inline = [A_1,A_2]
23
class B:
24
saveable = False
25
inline = [B_1,B_2]
26
27
class C:
28
saveable = True
29
inline = [C_1,C_2]
30
31
class Main:
32
inline =[A,B,C]
33
I want a function or a method that order the node according saveable attribute. I want the output like:
JavaScript
1
6
1
>>Main.inline
2
[B, C, A]
3
4
>>A.inline
5
[A_2,A_1]
6
and so on
if we plot the output is same like:
Advertisement
Answer
While I disagree with the approach, this is what you need to do: (I’ve modified the code as little as possible, and added tests at the bottom to prove it works)
JavaScript
1
55
55
1
import operator
2
3
class A_1:
4
saveable =True
5
6
class A_2:
7
saveable =False
8
9
class B_1:
10
saveable =True
11
12
class B_2:
13
saveable =False
14
15
class C_1:
16
saveable =False
17
18
class C_2:
19
saveable =True
20
21
class Ordered(type):
22
def __new__(cls, name, bases, attr):
23
new_klass = super(Ordered, cls).__new__(cls, name, bases, attr)
24
# Uncomment the line bellow after you've read the comment in all the
25
# way at the bottom of the code.
26
#
27
# new_klass.inline.sort(key=lambda x: x.__name__, reverse=True)
28
new_klass.inline.sort(key=operator.attrgetter('saveable'))
29
return new_klass
30
31
class A(metaclass=Ordered):
32
saveable = True
33
inline = [A_1,A_2]
34
35
class B(metaclass=Ordered):
36
saveable = False
37
inline = [B_1,B_2]
38
39
class C(metaclass=Ordered):
40
saveable = True
41
inline = [C_1,C_2]
42
43
class Main(metaclass=Ordered):
44
inline =[A,B,C]
45
46
# this differs from your example slightly, since you asked
47
# for `[B, C, A]`, in order to get that working, is just a
48
# matter of changing the `sort()` above, and uncommenting
49
# the commented line in the function. I left it there in
50
# case you REALLY wanted it. I figured this would be enough
51
# and the alternative just complicates things further
52
assert Main.inline == [B, A, C]
53
# assert Main.inline == [B, C, A]
54
assert A.inline == [A_2, A_1]
55