重复使用不同类方法的方法签名

发布于 2025-01-24 14:23:50 字数 434 浏览 0 评论 0原文

我想重复使用method1 classa clasta on Method1_1 classB以某种方式像接口一样。 什么是一种通用方法来指示/强制执行Method1_1具有与Method1_1的签名相同的签名?

class ClassA():
  def method1(self, a:int, b:str, c:list[str]):
    pass

class ClassB():
  class_a: ClassA

  def method1_1(self, a:int, b:str, c:list[str]):
    self.class_a(a,b,c)

I would like to reuse the method1 signature of ClassA on method1_1 ClassB somehow like an interface.
What is a general approach to indicate/enforce that method1_1 has the same signature as method1_1?

class ClassA():
  def method1(self, a:int, b:str, c:list[str]):
    pass

class ClassB():
  class_a: ClassA

  def method1_1(self, a:int, b:str, c:list[str]):
    self.class_a(a,b,c)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

再可℃爱ぅ一点好了 2025-01-31 14:23:50

您可以介绍抽象基类和抽象基类的装饰工:

import abc
from typing import List


class AbstractDataProcessor(abc.ABC):
    @abc.abstractmethod
    def process(self, a: int, b: str, c: List[str]): pass


class DataProcessor(AbstractDataProcessor):
    def process(self, a: int, b: str, c: List[str]):
        print(f"a: {a}, b: {b}, c: {c}")


class DataProcessorDecorator(AbstractDataProcessor):
    processor: AbstractDataProcessor

    def __init__(self, processor: AbstractDataProcessor):
        self.processor = processor

    def process(self, a: int, b: str, c: List[str]):
        self.processor.process(a, b, c)


if __name__ == '__main__':
    p = DataProcessorDecorator(DataProcessor())
    p.process(1, "2", ["1", "2", "3"])

You could introduces an abstract base class and a decorator for the abstract base class:

import abc
from typing import List


class AbstractDataProcessor(abc.ABC):
    @abc.abstractmethod
    def process(self, a: int, b: str, c: List[str]): pass


class DataProcessor(AbstractDataProcessor):
    def process(self, a: int, b: str, c: List[str]):
        print(f"a: {a}, b: {b}, c: {c}")


class DataProcessorDecorator(AbstractDataProcessor):
    processor: AbstractDataProcessor

    def __init__(self, processor: AbstractDataProcessor):
        self.processor = processor

    def process(self, a: int, b: str, c: List[str]):
        self.processor.process(a, b, c)


if __name__ == '__main__':
    p = DataProcessorDecorator(DataProcessor())
    p.process(1, "2", ["1", "2", "3"])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文