带下划线的方法和不带下划线的方法有什么区别,特别是那些由dir()方法列出的方法?

2024-05-01 15:06:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中使用dir()方法时,为什么返回的一些方法被下划线包围?我应该用这些方法吗?你知道吗

例如,dir([1,2,3,4,5,6])返回:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

这些方法中的最后九种是常规使用的方法。你知道吗

当我查看文档时,我很少看到这些方法是什么:

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

谢谢你。你知道吗


Tags: the方法addreducedocdirmethodattributes
1条回答
网友
1楼 · 发布于 2024-05-01 15:06:22

不同于其他语言(java,C++),Python中没有“私有”方法(即不能在定义它们的类之外调用方法)。因此,任何调用方都可以从任何对象调用内部方法。
按照惯例,您不应该调用对象的那些方法,以避免类的程序员没有预料到的不必要的后果。你知道吗

相关问题 更多 >