Python内置方法(又称魔法方法)
开胃菜(小例子、用法):
help(method)
查看帮助,按space或enter继续显示多的行数(-- More --),按ctrl+c退出。
如果想要查看有哪些方法,比如list有哪些方法,可以:
dir(list)
输出:
>>> dir(list)
['__add__', '__class__', '__contains__',
'__delattr__', '__delitem__', '__dir__',
'__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__',
'__sizeof__', '__str__',
'__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse',
'sort']
为什么len()在python中不是一个普通的方法?
来自流畅的python第一章
python还有哪些内置方法/函数?
python官方文档-内置函数:https://docs.python.org/zh-cn/3/library/functions.html
慢慢探索吧:
__eq__和==和is和id
起因:LeetCode 141. Linked List Cycle
解法:
#定义节点
class ListNode():
def __init__(self, x):
self.val = x
self.next = None
#这一点是可以自己重写的,如果不重写,那自定义类型默认就是把==当做is
def __eq__(self, other):
return self.val == other.val
class Solution():
def hasCycle_improved(self, head) -> bool:
'''
空间O(1)的做法: 快慢指针,slow一次走一步,fast一次走两步,如果有环
fast最后一定能追到slow(这一点可画图稍作推导)
另一个理解:相对速度
fast走两步,slow是走一步,**其实相对于slow来说,
fast是一个节点一个节点的靠近slow的**,所以fast一定可以和slow重合。
'''
pt1, pt2 = head, head
if not pt1:
return False
while pt1 != None and pt2 != None:
pt1 = pt1.next
pt2 = pt2.next
if pt2:
pt2 = pt2.next
if pt1 and pt2 and id(pt1) == id(pt2):
return True
#关于这里,代码随想录直接用的pt1 == pt2,其实就是在比地址id,而不是比value。
"""
By default, object implements eq() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented.
stackoverflow的优质解答
According to the object.eq() documentation,
__eq__的官方文档
the default (that is, in the object class) implementation for == is as follows:
True if x is y else NotImplemented
__eq__和__hash__要一致
python3中,在set,frozenset,dict这三种数据结构中,都要求键值key是可hash的,因为要保证key的唯一性。
而__hash__实际上是返回一个int值,用来唯一标记这个对象。
用户自定义类中,如果你没有实现__eq__和__hash__函数,那么class会继承到默认的__eq__和__hash__函数。如下:
————————————————
版权声明:本文为CSDN博主「anlian523」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/anlian523/article/details/80910808
流畅的Python:
如果你实现了一个类的__eq__ 方法,并且希望它是可散列的,那么它一定要
有个恰当的__hash__ 方法,保证在a == b 为真的情况下hash(a) == hash(b)也必定为真。否则就会破坏恒定的散列表算法,导致由这些对象所组成的字典和集合完全失去可靠性,这个后果是非常可怕的。另一方面,如果一个含有自定义的__eq__ 依赖的类处于可变的状态,那就不要在这个类中实现
hash 方法,因为它的实例是不可散列的。
help的工作原理
我发现dir(ListNode)并没有__help__的魔法方法,那么help(ListNode)是怎么实现的呢?
StackOverFlow上的一个优质回答:
Python的help方法究竟从哪里获得的帮助文档?
If you simply do, help(help), you will get
Help on _Helper in module site object:
class _Helper(__builtin__.object)
| Define the builtin 'help'.
| This is a wrapper around pydoc.help (with a twist).
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
|
| __repr__(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
basically, help gets its input from pydoc.help
. Quoting, pydoc documentation
For modules, classes, functions and methods, the displayed documentation is derived from the docstring (i.e. the doc attribute) of the object, and recursively of its documentable members. If there is no docstring, pydoc tries to obtain a description from the block of comment lines just above the definition of the class, function or method in the source file, or at the top of the module (see inspect.getcomments()).
The built-in function help() invokes the online help system in the interactive interpreter, which uses pydoc to generate its documentation as text on the console.
对于模块、类、函数和方法,显示的文档是从__doc__对象的文档字符串(即属性)派生的,并递归地从其可记录的成员中派生出来。如果没有文档字符串,pydoc尝试从源文件中类、函数或方法定义上方或模块顶部的注释行块中获取描述(参见 参考资料inspect.getcomments())。
内置函数help()调用交互式解释器中的在线帮助系统,该系统用于pydoc在控制台上将其文档生成为文本。
help和__doc__方法都可以输出一个对象的帮助文档:
def my_function():
'''Demonstrates triple double quotes
docstrings and does nothing really.'''
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
python使用什么魔法方法来实现整数对象的 +=
在 Python 中,实现整数对象的 += 运算符使用的是魔法方法 iadd。
该魔法方法用于实现可变对象的+=操作,例如整数。在 Python 中,整数是不可变对象,因此当使用 += 运算符时,Python 解释器会调用 iadd 方法来对整数对象进行更新。
python sum用的是什么魔法方法
在 Python 中,内置函数 sum 实现的功能是对可迭代对象中的元素求和。它使用了魔法方法 add 实现对元素的求和。
add 方法是 Python 的特殊方法,它实现了加法运算符(+)的功能。当我们对两个对象使用加法运算符时,Python 解释器会调用它们的 add 方法,来得到两个对象相加的结果。
python内置函数sum是如何实现的,是否与迭代器和魔法方法有关?
是的,Python 内置函数 sum 实现的功能是对可迭代对象的元素求和,它与迭代器和魔法方法有关。
当我们调用 sum 函数时,它首先会将可迭代对象转换为迭代器,然后通过迭代器遍历元素,最终实现求和的功能。
同时,它使用了魔法方法 add 实现加法运算符(+)的功能,对元素的加法操作在代码内部调用的就是 add 方法。
python 魔法方法是公有还是私有的
在 Python 中,魔法方法是公有的。它们通常以两个下划线开头和结尾,表示它们是 Python 的内部方法,但是可以被公开访问。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix