(P3)python类的特殊方法 init、getitem、len、call

python 类的特殊方法

参考资料
python解释器遇到特殊句法时,会去调用特殊方法,这些特殊方法以双下划线开头。

1、__init __ ()

该方法在对象创建时被解释器自动调用。

在这里插入图片描述

2、__getitem __ ()

getitem 获取实例对象的具体内容

p[key]

在这里插入图片描述

3、__len __()

len 计算数据长度

len( p)

举例

class Fun():
    def __init__(self, x_list):
        """ initialize the class instance
        Args:
            x_list: data with list type
        Returns:
            None
        """
        if not isinstance(x_list, list):
            raise ValueError("input x_list is not a list type")
        self.data = x_list
        print("intialize success")
    
    def __getitem__(self, idx):
        print("__getitem__ is called")
        return self.data[idx]
    
    def __len__(self):
        print("__len__ is called")
        return len(self.data)

fun = Fun(x_list=[1, 2, 3, 4, 5])
print(fun[2])
print(len(fun))


'''
intialize success
__getitem__ is called
3
__len__ is called
5
'''

4、__call __()

详解Python的__call__()方法
call:可以调用
p()
可调用对象:可以直接 p() 调用执行
自定义函数、Python内置函数、实例对象和实例方法 都是可调用对象。

说一下我的通俗理解:只要类当中定义了 call 方法,我们在实例化类的对象后, p() 会运行 call 方法下的内容。

在这里插入图片描述

# 自定义函数
def test():
    print("Function test() is called")
print("Function test() is callable: %s" % callable(test))
test()
test.__call__()
'''
Function test() is callable: True
Function test() is called
Function test() is called
'''

# 内置函数
print("Build-in function int() is callable: %s" % callable(int))
print(int(3))
print(int.__call__(3))
'''
Build-in function int() is callable: True
3
3
'''

# 实例对象
class Person(object):
    pass
c = Person()
print("Object c is callable: %s" % callable(c))
'''
Object c is callable: False
'''

class Person(object):
    def __call__(self):
        print("Method __call__() is called")
d = Person()
print("Object d is callable: %s" % callable(d))
d()
'''
Object d is callable: True
Method __call__() is called
'''

补充内容(单独记笔记,TODO)

1、类
2、类的实例对象
3、可调用对象:可以直接 p() 调用执行
自定义函数、Python内置函数、实例对象和实例方法 都是可调用对象。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值