Python中的Super方法实现问题及解决方案

1、问题背景

在Python中,super方法用于在子类中调用父类的方法。Guido van Rossum曾给出了一个纯Python实现的super方法,以便更好地理解其工作原理。然而,在这个实现中,存在一个问题:当传入的对象不是要调用的父类的实例时,该实现会出错。

2、解决方案

为了解决这个问题,需要对Guido的实现进行修改。具体来说,需要在__getattr__()方法中添加一个检查,以确保传入的对象是给定类型的实例。如果传入的对象不是给定类型的实例,那么就引发一个错误。

以下是修改后的__getattr__()方法:

python 复制代码
    def __getattr__(self, attr):
        if isinstance(self.__obj__, self.__type__):
            starttype = self.__obj__.__class__
        else:
            # 检查传入的对象是否是给定类型的实例
            if not isinstance(self.__obj__, self.__type__):
                raise TypeError("obj must be an instance or subtype of type")
            starttype = self.__obj__

        mro = iter(starttype.__mro__)
        for cls in mro:
            if cls is self.__type__:
                break
        # Note: mro is an iterator, so the second loop
        # picks up where the first one left off!
        for cls in mro:
            if attr in cls.__dict__:
                x = cls.__dict__[attr]
                if hasattr(x, "__get__"):
                    x = x.__get__(self.__obj__)
                return x
        raise AttributeError, attr

通过这个修改,就可以确保传入的对象是给定类型的实例,从而避免了错误的发生。

以下是修改后的代码示例:

python 复制代码
class Super(object):
    def __init__(self, type, obj=None):
        self.__type__ = type
        self.__obj__ = obj

    def __get__(self, obj, type=None):
        if self.__obj__ is None and obj is not None:
            return Super(self.__type__, obj)
        else:
            return self

    def __getattr__(self, attr):
        # 检查传入的对象是否是给定类型的实例
        if not isinstance(self.__obj__, self.__type__):
            raise TypeError("obj must be an instance or subtype of type")

        if isinstance(self.__obj__, self.__type__):
            starttype = self.__obj__.__class__
        else:
            starttype = self.__obj__

        mro = iter(starttype.__mro__)
        for cls in mro:
            if cls is self.__type__:
                break
        # Note: mro is an iterator, so the second loop
        # picks up where the first one left off!
        for cls in mro:
            if attr in cls.__dict__:
                x = cls.__dict__[attr]
                if hasattr(x, "__get__"):
                    x = x.__get__(self.__obj__)
                return x
        raise AttributeError, attr

class A(object):
    def m(self):
        '''  m in A'''
        return "A"

class B(A):
    def m(self):
        '''  m in B'''
        return "B" + Super(B, self).m()

class C(A):
    def m(self):
        ''' m in C '''
        return "C" + Super(C, self).m()

class D(C):
    def m(self):
        ''' m in D'''
        return "D" + Super(B, self).m()

print(D().m()) # "DCBA"

现在,该代码就可以正确地运行,并且不会引发错误。

相关推荐
第九序言T11 分钟前
数据分析岗 Pandas 面试题 20 道(上):概念与读代码
python·数据分析·pandas·数据处理
Dmz丶12 分钟前
前端转 AI 100 天 Day 37:Few-shot 与 CoT——让模型学会“推理”
python
孟健33 分钟前
我用Grok Bot本地剪口播视频,3段提示词搞定气口切除、字幕与封面
人工智能·python·aigc
2601_966949651 小时前
如何封装 qd.klines.batch(),让批量 K 线查询函数在多个策略中复用?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
神仙别闹2 小时前
基于Python实现英词语自动对齐系统
开发语言·python
老歌老听老掉牙3 小时前
圆柱端面四平面交线及其在yoz面投影的几何解析与 Python 实现
开发语言·python·平面
我要见SA姐13 小时前
Chrome 扩展安全攻防实录:从权限滥用到供应链投毒
运维·人工智能·python·机器学习·自动化
2601_962885723 小时前
给 backtrader 接 A 股数据:用 AlphaFeed 喂PandasData
python
YYYing.4 小时前
【Agent系列 (十一) 】上下文工程
人工智能·python·ai·agent·上下文工程
计算机毕业编程指导师4 小时前
基于深度学习的光伏组件红外图像缺陷识别系统设计与实现
人工智能·python·深度学习·目标检测·毕业设计·课程设计·光伏