【问题标题】:Python classes: having instance method in one class point to instance method in another classPython类:一个类中的实例方法指向另一个类中的实例方法
【发布时间】:2019-08-27 00:35:36
【问题描述】:

我有一个类(我称之为“大师类”),它使用来自多个其他类的实例方法。其他类在__init__ 上导入并存储为私有实例属性。

我想使用其他类的实例方法,具有以下属性:

  • 不重写主类中的文档字符串或签名
  • autodoc 解析来自其他类的文档字符串,就像它们是主类的文档字符串一样

目前,我的设置方式:

class OtherClass:
    """Some other class that I import."""

    def __init__(self):
        pass

    def print_num(self, num: float = 15) -> None:
        """Print a num.

        Args:
            num: Number to print

        """
        print(num)

from .other import OtherClass


class MasterClass:

    def __init__(self, other_class: OtherClass):
        """Create master class with a bunch of other classes.

        For simplicity, I only included one class here as an arg.

        Args:
            other_class: Houses some methods

        """
        self._other_class = other_class

    def print_num(self, num: float = 15):
        """Print a num.

        Args:
            num: Number to print

        """
        self._other_class.print_num(num)

要加入OtherClass.print_num,我必须:

  1. 手动复制签名
  2. 手动复制文档字符串(因为我希望我的 Sphinx 文档准确无误)
  3. MasterClass的方法中调用OtherClass的方法,手动传入所有的args和kwargs

有没有更好的方法来做到这一点?

提前感谢您的指导。

【问题讨论】:

    标签: python class methods attributes docstring


    【解决方案1】:

    函数wraps from the module functools就是你需要的:

    from functools import wraps
    
    class OtherClass:
        def print_num(self, num: float=15) -> None:
            """Print a num.
    
            Args:
                num: Number to print
    
            """
            print(num)
    
    class MasterClass:
        def __init__(self, other_class: OtherClass):
            self._other_class = other_class
    
        @wraps(OtherClass.print_num)
        def print_num(self, num=15):
            self._other_class.print_num(num)
    
    print(MasterClass.print_num.__doc__)
    print(MasterClass.print_num.__annotations__)
    

    输出:

    Print a num.
    
            Args:
                num: Number to print
    
    
    {'num': <class 'float'>, 'return': None}
    

    您仍然需要进行显式调用。

    注意:您的设计是facade pattern 的特例。

    【讨论】:

    • 非常感谢您提供的信息性回答,我以前不知道外观模式!
    猜你喜欢
    • 2015-06-10
    • 2016-01-15
    • 1970-01-01
    • 2014-10-27
    • 2021-09-17
    • 2014-11-05
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    相关资源
    最近更新 更多