我刚刚创建了一个简单的python类,以了解有关魔术方法的更多信息,并使用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
对类的属性名称进行排序,因此您可以使用包装器函数对其进行修补,该包装器函数根据是否使用其名称对属性进行重新排序等于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.
...