calling help(MyClass) also shows base class attributes: how to avoid that?

微笑、不失礼 提交于 2019-12-25 02:09:44

问题


MyClass is derived from "list": MyClass(list) I would like to document MyClass nicely. Unfortunately, when trying help(MyClass), I get my own documentation, but I also get a lot of stuff about "list".

Would there be a simple way to control that? I read something about metaclasses, but I was unable to do something.

Thanks for your suggestions,

Michel


回答1:


Well, that is what help does. It introspects into your class and show the name and the associated __doc__ for each callable attribute in the class, and that is not customizable.

Attributes of the superclass are considered attributes of the class, and are reached in the introspection Python's help do.

Metaclasses could even be used to customize the output one gets when he does "dir" on your class - but they do not change the output of the help text. To change "dir" output, create a metaclass implementing a __dir__ method, and return a list of what you want visible as dir's output.

class M(type):
   def __dir__(self):
       return []  # blank dir contents

class MyList(list, metaclass=M):
   ...

On the other hand, the help contents displayed for list attributes are not that verbose, and can actually be helpful - if you override any methods to do something different than described, the incorrect text won't show anyway. So you might just live with it.

Another tip is that instead of subclassing list you might prefer to subclass collections.abc.MutableSequence instead, and use an inner agregated (normal) list to keep your data: that will require you to implement a lot less methods to have your class working properly as a sequence and is preferable in most cases to subclass list. That won't change help's verbosity though.



来源:https://stackoverflow.com/questions/46811688/calling-helpmyclass-also-shows-base-class-attributes-how-to-avoid-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!