Python:类属性的协议

von4xj4u  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(84)

我的方法需要一个具有属性pattern和函数handle的对象。为此,我编写了一个具有这两个成员的Protocol示例。考虑以下代码:

class Handler(typing.Protocol):
    """Handler protocol"""

    pattern: re.Pattern

    @staticmethod
    def handle(match: re.Match) -> str:
        pass

def f(obj: Handler, text: str):
    output = []
    for match in re.finditer(obj.pattern, text):
        output.append(obj.handle(match))
    return output

class MyHandler(Handler):
    pattern = re.compile("hello world")

    @staticmethod
    def handle(match: re.Match) -> str:
        return "hi there"

f(MyHandler, 'hello world, what a nice morning!')

字符串
但是,当我使用MyHandler调用此函数时,IDE(PyCharm)会发出以下警告:
应为类型“ReplacerProtocol”,而得到的是“Type[CitationReplacer]"
当我从protocol类中删除pattern属性时,此警告消失。当我更改协议以要求@property或名称为pattern的函数时,会发出相同的警告。
在Python中定义接口的正确方法是什么?

6ie5vjzr

6ie5vjzr1#

直接在XML协议中的pattern属性上使用@property装饰器。我使用了obj.pattern.search方法而不是re. finditer。

from typing import Protocol
import re

class Handler(Protocol):
    """Handler protocol"""

    @property
    def pattern(self) -> re.Pattern:
        pass

    @staticmethod
    def handle(match: re.Match) -> str:
        pass

def f(obj: Handler, text: str):
    output = []
    matches = obj.pattern.finditer(text)
    for match in matches:
        output.append(obj.handle(match))
    return output

class MyHandler:
    @property
    def pattern(self) -> re.Pattern:
        return re.compile("hello world")

    @staticmethod
    def handle(match: re.Match) -> str:
        return "hi there"

result = f(MyHandler(), 'hello world, what a nice morning!')
print(result)

字符串

相关问题