我正在处理一个项目,它包含来自不同文件中几个模块的类的长层次结构。你知道吗
我想知道继承链中类C什么时候得到了属性A (然后我可以得到定义了C的模块M并检查代码)
考虑下面的代码示例,假设除GrandChildOf1ChildOf2
之外的所有类都在其他模块中,是否有命令,例如:attribute_base(o4,'a')
,输出:Base1
?你知道吗
class SweetDir:
def __sweet_dir__(self):
"""
Same as dir, but will omit special attributes
:return: string
"""
full_dir = self.__dir__()
sweet_dir = []
for attribute_name in full_dir:
if not ( attribute_name.startswith('__')
and attribute_name.endswith('__')):
#not a special attribute
sweet_dir.append(attribute_name)
return sweet_dir
class Base1(SweetDir):
def __init__(self):
super(Base1,self).__init__()
self.a = 'a'
class Base2(SweetDir):
def __init__(self):
super(Base2,self).__init__()
self.b = 'b'
class ChildOf1 (Base1):
def __init__(self):
super(ChildOf1,self).__init__()
self.c = 'c'
class GrandChildOf1ChildOf2 (Base2,ChildOf1):
def __init__(self):
super(GrandChildOf1ChildOf2,self).__init__()
self.d = 'd'
o1 = Base1()
o2 = Base2()
o3 = ChildOf1()
o4 = GrandChildOf1ChildOf2()
print(o1.__sweet_dir__())
print(o2.__sweet_dir__())
print(o3.__sweet_dir__())
print(o4.__sweet_dir__())
输出:
['a']
['b']
['a', 'c']
['a', 'b', 'c', 'd']
我不认为有一个内置的功能,但类似的工作(它需要改进):
这将返回类的第一个基类,该基类具有您要查找的属性。这显然不是完美的。如果两个或多个基类具有相同的属性(具有相同的名称),则它可能不会返回获得该属性的实际类,但在您的示例中,它会起作用。 [用AKX注释更新:使用
__mro__
实际上可以解决这个问题][更新:有一种方法不需要实例就可以做到这一点,遵循这个有大量文档记录的答案:list-the-attributes-of-a-class-without-instantiating-an-object]
getmembers
提供类的每个成员,包括我们想要的init方法。我们需要检查它是否真的是一个函数(hasattr(member[1], "__code__"))
,因为如果没有为类定义__init__
函数(如示例中的SweetDir),这将返回一个包装器描述符。我们在稀有的(可能的?)案例有几种__init__
方法。你知道吗相关问题 更多 >
编程相关推荐