Python справка, например, не показывает __init__ в начале - PullRequest
2 голосов
/ 06 февраля 2020

Я только что создал простой класс python, чтобы узнать больше о методах magi c, и я использовал 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})"

here is screenshot of the REPL help output

1 Ответ

2 голосов
/ 06 февраля 2020

Функция help - это оболочка pydoc.help, которая использует pydoc.sort_attributes для сортировки имен атрибутов класса, так что вы можете исправить это с помощью функции-оболочки, которая пересортирует атрибуты, основанные на том, равно ли его имя __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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...