wlo*_*wlo 11 python python-decorators python-3.8
有人可以澄清将属性定义为协议一部分的普遍接受的方式吗?
我一直这样做:
from typing import Protocol
class MyProtocol(Protocol):
@property
def my_property(self):
""" Classes should have a my_property to conform to MyProtocol """
Run Code Online (Sandbox Code Playgroud)
但是 Pycharm 的内置 linter 不断抱怨“Getter 应该返回或产生一些东西”,因此我很困惑。引发 aNotImplementedError会使 linter 消息消失,但这样做似乎更适合抽象类而不是协议。
小智 -2
他们是分开的。属性是允许像属性一样调用函数。例如
class MyClassProtocol(Protocol):
def example() -> int: ...
class MyClass(MyClassProtocol):
@property
def example() -> int:
return 5
tmp = MyClass()
tmp.example
Run Code Online (Sandbox Code Playgroud)
5
这就是为什么您的 IDE 会选择必须返回或产生某些内容,因为属性需要返回值。
| 归档时间: |
|
| 查看次数: |
1502 次 |
| 最近记录: |