如何解决如何在super调用的类方法中找到当前基类?
如何在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
解决方法
一个人可以使用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())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。