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



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

  • 类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

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

最新更新