Python 帮助例如开头不显示 __init__

Python help for instance does not show __init__ at the beginning

我刚刚创建了一个简单的 python class 来学习更多关于魔术方法的知识,我使用 REPL 来实例化一个对象。但是当我键入 help(<instance>) 时,它不会在开头显示 __init__() 方法。如何让 init 方法显示在帮助的开头。这很重要,因为人们应该看到 init 方法才能知道如何实例化它。

class vector:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __rmul__(self,const):
        if type(const) == int:
            return vector(self.x*const,self.y*const)
        else:
            raise TypeError(f"an int type is expected but {type(const)} is provided")

    def __mul__(self,const):
        return vector(self.x*const,self.y*const)

    def __add__(self,other):
        if type(self) == type(other):
            return vector(self.x+other.x, self.y+other.y)
        else:
            raise TypeError(f"type of other should be {type(other)}")

    def __radd__(self,other):
        if type(self) == type(other):
            return vector(self.x+other.x, self.y+other.y)
        else:
            raise TypeError(f"type of other should be {type(other)}")

    def __eq__(self,other):
        if type(self) == type(other) and self.x == other.x and self.y == other.y:
            return True
        else:
            return False

    def __len__(self):
        return (self.x**2 + self.y**2)

    def __repr__(self):
        return f"vector({self.x},{self.y})"

help函数是pydoc.help的包装器,它使用pydoc.sort_attributes对class的属性名称进行排序,所以你可以用一个补丁根据其名称是否等于 __init__:

对属性重新排序的包装函数
import pydoc

def sort_attributes_wrapper(attrs, object):
    orig_sort_attributes(attrs, object)
    attrs.sort(key=lambda t: t[0] != '__init__')

orig_sort_attributes = pydoc.sort_attributes
pydoc.sort_attributes = sort_attributes_wrapper

因此 help(vector) 输出:

Help on class vector in module __main__:

class vector(builtins.object)
 |  vector(x, y)
 |  
 |  Methods defined here:
 |  
 |  __init__(self, x, y)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __add__(self, other)
 |  
 |  __eq__(self, other)
 |      Return self==value.
...

演示:https://repl.it/@blhsing/ThinScratchyParallelalgorithm