【问题标题】:Can a class attribute shadow a built-in in Python?类属性可以隐藏 Python 中的内置函数吗?
【发布时间】:2022-01-05 17:07:05
【问题描述】:

如果有这样的代码:

class Foo():
   def open(self, bar):
       # Doing some fancy stuff here, i.e. opening "bar"
       pass

当我使用 flake8-builtins 插件运行 flake8 时,我得到了错误

A003 class attribute "open" is shadowing a python builtin

我不明白该方法如何可能会影响内置 open 函数,因为该方法只能使用实例调用(即self.open("")someFoo.open(""))。是否有其他方式代码期望调用内置最终调用该方法?或者这是flake8-builtins插件的误报?

【问题讨论】:

    标签: python built-in flake8


    【解决方案1】:

    不是一个真正的实际案例,但如果您想在初始化影子函数后在类级别使用内置函数,您的代码将会失败:

    class Foo:
        def open(self, bar):
            pass
    
        with open('myfile.txt'):
            print('did I get here?')
    
    >>> TypeError: open() missing 1 required positional argument: 'bar'
    

    其他内置函数也是如此,例如print

    class Foo:
        def print(self, bar):
            pass
    
        print('did I get here?')
    
    >>> TypeError: print() missing 1 required positional argument: 'bar'
    

    【讨论】:

    • 确实如此,但是类中的函数是用于类对象的。 self.open()open() 不同,所以没有问题。
    • 我接受这个答案,因为它显示了该方法确实会影响内置函数的场​​景。
    【解决方案2】:

    您的代码应该没有问题。只要该函数是用self.open() 而不是open() 引用的,它就应该可以工作。只需确保该类还没有 open() 函数即可。

    【讨论】:

    • 我担心的是相反的情况:写 open() 并最终调用方法而不是内置函数。
    • 是的,但这不会发生,因为open()self.open() 是不同的,不能互换。
    猜你喜欢
    • 1970-01-01
    • 2014-04-13
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    相关资源
    最近更新 更多