【问题标题】:Identify the superclass that defines a class-level variable识别定义类级变量的超类
【发布时间】:2018-10-01 18:29:58
【问题描述】:

在python中多重继承的情况下,有没有办法识别一个类级变量是从哪个超类获取的?

我试图用谷歌搜索的所有尝试绝大多数都是关于如何获取属性而不是找出它来自哪里:

https://www.google.com/search?q=pythin+which+super+class+defines+attr

https://www.google.com/search?q=python+which+super+class+has+attribute&oq=python+which+super+class+has+attr

https://www.google.com/search?q=python+which+super+class+attribute+obtained+from

我想我可以使用 inspect.getmro(cls) 手动单步执行 MRO。但我找不到任何更优雅的解决方案。只是想知道是否有人知道。

编辑

举个具体的例子:

class Super1(object):
    __class_attribute__ = "Foo"

class Super2(object):
    pass

class Derived(Super1, Super2):
    pass

d = Derived()

parent_cls = some_function_to_get_defining_class(d.__class_attribute__) # <-- should return `Super1`

【问题讨论】:

标签: python


【解决方案1】:

__qualname__ 属性指示方法从哪个类继承。但是,这只返回一个字符串,而不是超类本身。如果您需要超类进行元编程,我认为您将不得不深入研究 MRO。

class A:
    def a(self):
        return 1
    def b(self):
        return 2

class B:
    def b(self):
        return 2.5
    def c(self):
        return 3

class C(A,B):
    pass

使用:

C.b.__qualname__
# returns:
'A.b'

但是,这不适用于使用抽象方法定义接口时,因为该方法必须被覆盖。

from abc import abstractmethod

class A:
    def a(self):
        return 1

    @abstractmethod
    def b(self):
        pass

class C(A):
    def b(self):
        return 100

C.b.__qualname__
# returns:
'C.b'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-09
    • 2015-02-03
    • 2022-01-13
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多