合并班级成员 [英] Merging Class Members
本文介绍了合并班级成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出这样的类结构:
class A:
dependencies = ["x", "y"]
class B(A):
dependencies = ["z"]
class C(A):
dependencies = ["n", "m"]
class D(C):
dependencies = ["o"]
我想知道是否有可能编写一个执行以下操作的函数(最好是生活在A类上):
I want to know if it's possible to write a function (preferably living on class A) that does something along these lines:
@classmethod
def get_all_dependencies(cls):
return super().get_all_dependencies() + cls.dependencies
对于上述类别,预期输出为:
For the above classes, the expected output would be:
>>> A.get_all_dependencies():
["x", "y"]
>>> B.get_all_dependencies():
["x", "y", "z"]
>>> C.get_all_dependencies():
["x", "y", "n", "m"]
>>> D.get_all_dependencies():
["x", "y", "n", "m", "o"]
显然,上面的代码不起作用-它只返回我调用的类的依赖项
。我不确定如何在所有课程上递归使用它? (我要隐藏 hasattr
检查以确保父类调用 get_all_dependencies()
。)
Obviously the above code doesn't work - it just returns the dependencies
of the class I call it on. I'm not sure how to get it to work recursively across all the classes? (I'm eliding a hasattr
check to ensure the parent class call get_all_dependencies()
.)
推荐答案
走 mro
并抓住依赖项是我要做的:
Walk the mro
and grab the dependencies is what I'd do:
@classmethod
def get_dep(cls):
return [d for c in cls.mro()[:-1] for d in getattr(c, 'dependencies')]
其中 cls.mro()[:-1]
用于排除 object
。
这将返回:
>>> A.get_dep()
['x', 'y']
>>> B.get_dep()
['z', 'x', 'y']
>>> C.get_dep()
['n', 'm', 'x', 'y']
>>> D.get_dep()
['o', 'n', 'm', 'x', 'y']
这篇关于合并班级成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文