gpt4 book ai didi

python - 为什么裸 Python 装饰器(没有@)不会产生编译器错误?

转载 作者:行者123 更新时间:2023-12-01 15:43:24 26 4
gpt4 key购买 nike

只是打错了:我忘了在属性装饰器之前添加@。花了大约 1 小时才找出问题所在。这是一个例子:

class Woo(object):
@property
def success(self):
return True

property
def failure(self):
return False

if __name__ == '__main__':
woo = Woo()
print(f'success={woo.success}')
print(f'failure={woo.failure}')
print(f'It\'s fine to call failure()={woo.failure()}')

结果是:

success=True
failure=<bound method Woo.failure of <__main__.Woo object at 0x0000016050D4F6D8>>
It's fine to call failure()=False

我想知道为什么 Python 编译器在语法中允许“裸装饰器”(例如,没有装饰器前缀 @ 的属性)以及它在语义上的含义。

最佳答案

让符号无目的地四处漂浮是完全合法的,类似于:

a = 1
a # Perfectly legal, although a thorough linter* will cause a warning

在您的示例中,它只是对 property 类的顶级引用,不用于任何用途,类似于您有:

class MyClass:
a = 1

a # Legal, but causes a warning since it has no purpose
def meth(self):
pass

1 # Also legal but useless
def another_meth(self):
pass

它没有被当作装饰器;在不用于任何用途的上下文中,它被视为对 property 类的简单引用。


* Pycharm 发出警告 Statement seems to have no effect

关于python - 为什么裸 Python 装饰器(没有@)不会产生编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com