问题
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