调用help(MyClass)还显示基类属性:如何避免这种情况? [英] calling help(MyClass) also shows base class attributes: how to avoid that?

查看:110
本文介绍了调用help(MyClass)还显示基类属性:如何避免这种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MyClass源自列表":MyClass(list) 我想很好地记录MyClass. 不幸的是,当尝试帮助(MyClass)时, 我有自己的文档,但也有很多有关列表"的内容.

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.

感谢您的建议,

米歇尔

推荐答案

好吧,这就是help的作用.它会对您的类进行自省,并为该类中的每个可调用属性显示名称和关联的__doc__,并且不能自定义.

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.

超类的属性被认为是该类的属性,并且可以在Python的自省中实现.

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

元类甚至可以用来自定义当他在您的类上执行"dir"操作时得到的输出-但它们不会更改帮助文本的输出.要更改"dir"输出,请创建一个实现__dir__方法的元类,并返回要显示为dir输出的列表.

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):
   ...

另一方面,为list属性显示的帮助内容不是那么冗长,实际上可以有所帮助-如果您重写任何方法来执行与所描述的不同的操作,则无论如何都不会显示错误的文本.因此,您可能会忍受它.

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.

另一个提示是,您可能更喜欢子类collections.abc.MutableSequence,而不是子类list,而是使用内部聚合的(常规)列表来保存数据:这将需要您实现更少的方法来拥有您的数据类可以按顺序正常工作,并且在大多数情况下比子列表更可取.但是,这不会改变help的详细程度.

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.

这篇关于调用help(MyClass)还显示基类属性:如何避免这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆