【问题标题】:How can I find the current base class in a classmethod invoked by super?如何在 super 调用的类方法中找到当前的基类?
【发布时间】:2021-02-14 14:46:35
【问题描述】:

如何在 super 调用的类方法中找到当前的基类?

  • B 类继承自 A
  • 两种数据方法中的代码必须相同,并且不应包含像 A 或 B 这样的文字类引用

我希望方法数据收集基类的 _data 值。

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

【问题讨论】:

    标签: python-3.x python-2.7 oop inheritance super


    【解决方案1】:

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

    • B 类继承自 A
    • 两种数据方法中的代码必须相同,并且不应包含像 A 或 B 这样的文字类引用
    class A:
        _data = "A data"
        @classmethod
        def data(cls):
            super_instance = super()
            this_cls = super_instance.__thisclass__
            try:
                other_data = super_instance.data()
            except AttributeError:
                return [this_cls._data]
            return [this_cls._data] + other_data
    
    class B(A):
        _data = "B data"
        @classmethod
        def data(cls):
            super_instance = super()
            this_cls = super_instance.__thisclass__
            try:
                other_data = super_instance.data()
            except AttributeError:
                return [this_cls._data]
            return [this_cls._data] + other_data
    
    B.data()
    # ['B data', 'A data']
    

    或者可以将其重构为更短的:

    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())
    

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 2010-09-15
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多