Python 3 __getattr__的行为与Python 2不同?

 小时候V有时候 发布于 2023-02-12 13:23

我需要编写一个实现32位无符号整数的类,就像它们在C编程语言中一样.我最关心的是二元转换,但我通常希望我的班级:

    具有相同的接口,int具有与工作int正常

    我的U32类(int + U32,U32+ int等)的任何操作也返回U32

    是纯python - 我不想使用NumPy,ctypes等.

正如在这个答案中可以找到的,我得到了一个在Python 2下运行的解决方案.最近我尝试在Python 3下运行它并注意到虽然以下测试代码在旧版本的Python下工作正常,但Python 3引发了一个错误:

class U32:
    """Emulates 32-bit unsigned int known from C programming language."""

    def __init__(self, num=0, base=None):
        """Creates the U32 object.

        Args:
            num: the integer/string to use as the initial state
            base: the base of the integer use if the num given was a string
        """
        if base is None:
            self.int_ = int(num) % 2**32
        else:
            self.int_ = int(num, base) % 2**32

    def __coerce__(self, ignored):
        return None

    def __str__(self):
        return "" % (id(self), self.int_)

    def __getattr__(self, attribute_name):
        print("getattr called, attribute_name=%s" % attribute_name)
        # you might want to take a look here:
        # /sf/ask/17360801/
        r = getattr(self.int_, attribute_name)
        if callable(r):  # return a wrapper if integer's function was requested
            def f(*args, **kwargs):
                if args and isinstance(args[0], U32):
                    args = (args[0].int_, ) + args[1:]
                ret = r(*args, **kwargs)
                if ret is NotImplemented:
                    return ret
                if attribute_name in ['__str__', '__repr__', '__index__']:
                    return ret
                ret %= 2**32
                return U32(ret)
            return f
        return r

print(U32(4) / 2)
print(4 / U32(2))
print(U32(4) / U32(2))

这是错误:

Traceback (most recent call last):
  File "u32.py", line 41, in 
    print(U32(4) / 2)
TypeError: unsupported operand type(s) for /: 'U32' and 'int'

getattr在Python 3中看起来根本没有调用这个技巧.为什么会这样?如何在Python 2和3下使用此代码?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有