【问题标题】:What is the difference between underscored methods and non-underscored methods, specifically those that are listed by the dir() method?下划线方法和非下划线方法之间有什么区别,特别是那些由 dir() 方法列出的方法?
【发布时间】:2017-06-03 03:27:55
【问题描述】:

在 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']

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

当我查看文档时,我几乎看不到这些方法是什么:

如果对象有一个名为 __dir__() 的方法,该方法将被调用并且必须返回属性列表。这允许实现自定义 __getattr__() 或 __getattribute__() 函数的对象自定义 dir() 报告其属性的方式。

谢谢。

【问题讨论】:

标签: python methods


【解决方案1】:

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

【讨论】:

  • 那么这些是python本身而不是用户在相应数据类型上使用的方法?
  • @DirkDunn,是的,这些方法是由 python 本身使用的——通常是双下划线的。但是,类本身(如上面示例中的类“列表”)可能会以在类外使用不安全的方式使用其中一些方法。第三方类通常在方法名称前有一个下划线。变量和常量遵循相同的约定。
猜你喜欢
  • 1970-01-01
  • 2020-06-25
  • 2012-10-16
  • 1970-01-01
  • 2011-10-19
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
相关资源
最近更新 更多