gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:23:13 26 4
gpt4 key购买 nike

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

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

['__add__',
'__类(class)__',
'__包含__',
'__delattr__',
'__delitem__',
'__delslice__',
'__doc__',
'__eq__',
'__格式__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getslice__',
'__gt__',
'__哈希__',
'__我加__',
'__imul__',
'__在里面__',
'__iter__',
'__le__',
'__长度__',
'__lt__',
'__mul__',
'__ne__',
'__新的__',
'__减少__',
'__reduce_ex__',
'__repr__',
'__反转__',
'__rmul__',
'__setattr__',
'__设置项__',
'__setslice__',
'__sizeof__',
'__str__',
'__subclasshook__',
'附加',
'数数',
'延长',
'指数',
'插入',
'流行音乐',
'消除',
'撤销',
'排序']

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

当我检查文档时,我对这些方法的了解很少:

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.

谢谢。

最佳答案

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

关于python - 带下划线的方法和不带下划线的方法有什么区别,特别是 dir() 方法列出的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41724719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com