首页 » InfoTech »

Python对象的特殊方法

2018年9月30日 / 3次阅读
Python

打开支付宝首页,搜索“529018372”,即可领取红包!可重复领。

特色图片

Python对象中有一些方法,前后以两个下划线开始和结束,这些方式都是一些特殊方法,比如对象创建时调用的__init__方法。

 

There are certain special methods which have special significance in classes such as the __init__ and __del__ methods whose significance we have already seen.

Generally, special methods are used to mimic certain behavior. For example, if you want to use the x[key] indexing operation for your class (just like you use for lists and tuples) then just implement the __getitem__() method and your job is done. If you think about it, this is what Python does for the list class itself!

Some useful special methods are listed in the following table. If you want to know about all the special methods, then a huge list is available in the Python Reference Manual.

__init__(self, ...)

This method is called just before the newly created object is returned for usage.

__del__(self)

Called just before the object is destroyed

__str__(self)

Called when we use the print statement with the object or when str() is used.

__lt__(self, other)

Called when the less than operator ( < ) is used. Similarly, there are special methods for all the operators (+, >, etc.)

__getitem__(self, key)

Called when x[key] indexing operation is used.

__len__(self)

Called when the built-in len() function is used for the sequence object.

本文链接:http://www.maixj.net/ict/python-teshu-method-19045
云上小悟 麦新杰(QQ:1093023102)

相关文章

评论是美德

无力满足评论实名制,评论对非实名注册用户关闭,有事QQ:1093023102.


前一篇:
后一篇:

栏目精选

云上小悟,麦新杰的独立博客

Ctrl+D 收藏本页

栏目

AD

ppdai

©Copyright 麦新杰 Since 2014 云上小悟独立博客版权所有 备案号:苏ICP备14045477号-1。云上小悟网站部分内容来源于网络,转载目的是为了整合信息,收藏学习,服务大家,有些转载内容也难以判断是否有侵权问题,如果侵犯了您的权益,请及时联系站长,我会立即删除。

网站二维码
go to top