Python 3.x 如何在super调用的classmethod中找到当前基类?

Python 3.x 如何在super调用的classmethod中找到当前基类?,python-3.x,python-2.7,oop,inheritance,super,Python 3.x,Python 2.7,Oop,Inheritance,Super,如何在super调用的classmethod中找到当前基类 B类继承自A类 两个数据方法中的代码必须相同,并且不应包含像a或B这样的文本类引用 我希望方法数据收集基类上的_数据值 class A: _data = "A data" @classmethod def data(cls) -> list[str]: # gather data here too, we may have N number of inheritance classes

如何在super调用的classmethod中找到当前基类

  • B类继承自A类
  • 两个数据方法中的代码必须相同,并且不应包含像a或B这样的文本类引用
我希望方法数据收集基类上的_数据值

class A:
  _data = "A data"
  @classmethod
  def data(cls) -> list[str]:
    # gather data here too, we may have N number of inheritance classes so we should try to invoke super here too

class B(A):
  _data = "B data"
  @classmethod
  def data(cls) -> list[str]:
    # gather data here and invoke super to gather data from A also

可以使用
super()获取当前基类
使用此解决方案,我们可以编写满足这些要求的以下代码:

  • B类继承自A类
  • 两个数据方法中的代码必须相同,并且不应包含像a或B这样的文本类引用
或者可以将其重构为较短的:

class DataGatherer:
    @staticmethod
    def gather_data(super_instance):
        this_cls = super_instance.__thisclass__
        try:
            other_data = super_instance.data()
        except AttributeError:
            return [this_cls._data]
        return [this_cls._data] + other_data


class A(DataGatherer):
    _data = "A data"
    @classmethod
    def data(cls):
        return cls.gather_data(super())

class B(A):
    _data = "B data"
    @classmethod
    def data(cls):
        return cls.gather_data(super())
class DataGatherer:
    @staticmethod
    def gather_data(super_instance):
        this_cls = super_instance.__thisclass__
        try:
            other_data = super_instance.data()
        except AttributeError:
            return [this_cls._data]
        return [this_cls._data] + other_data


class A(DataGatherer):
    _data = "A data"
    @classmethod
    def data(cls):
        return cls.gather_data(super())

class B(A):
    _data = "B data"
    @classmethod
    def data(cls):
        return cls.gather_data(super())