在 python 中导入包含重载打印函数的自定义模块生成属性错误

Importing custom module containing overloaded print function in python generating attribute error

我正在使用 Pycharm IDE。我正在尝试导入一个文件,这导致了属性错误。我创建了一个 Python 文件 testing.py:

    import decimal

    def print(num, round_digits=3):
            if (type(num) == float or type(num) == decimal.Decimal) and round_digits >=0:
                    __builtins__.print(round(num, round_digits))
            else:
                    __builtins__.print(num)

在同一个目录下,我写了一个文件test.py:

    import testing

    testing.print(0.17 * 0.3064,2)

运行 此文件产生此错误:

Traceback (most recent call last):

File "C:/Users/anura/PycharmProjects/pythonProject/test.py", line 3, in <module>
    testing.print(0.17 * 0.3064,2)

File "C:\Users\anura\PycharmProjects\pythonProject\testing.py", line 5, in print
    __builtins__.print(round(num, round_digits))

AttributeError: 'dict' object has no attribute 'print'

您想使用 builtins,而不是 __builtins____builtins__的内容是实现细节。

所以将您的代码更改为

import builtins    
import decimal

def print(num, round_digits=3):
    if (type(num) == float or type(num) == decimal.Decimal) and round_digits >=0:
        builtins.print(round(num, round_digits))
    else:
        builtins.print(num)

附加建议:您可能希望将 type(num) == float 替换为 isinstance(num, float)isinstance 允许给定 class.

的子classes