魔术方法__getitem__

Python中的魔术方法_getitem_

python中有许多的魔术方法,下文主要对_getitem_()进行介绍。__

在python中_getitem_(self, key):方法被称为魔法方法,这个方法返回所给键对应的值。

  1. 当对象是序列时,键是整数。当对象是映射时(字典),键是任意值

  2. 在定义类时,如果希望能按照键取类的值,则需要定义__getitem__方法

  3. 如果给类定义了_getitem__方法,则当按照键取值时,可以直接返回

    __getitem__方法执行的结果

class test_getitem():
    def __init__(self):
        self.num1 = 50

    # 定义__getitem__(),key为test_getitem的键
    def __getitem__(self, key):
        num2 = self.num1 + key
        return num2

test = test_getitem()
print(test[100])    # 150

对比

class test_getitem():
    def __init__(self):
        self.num1 = 50

    # 定义__getitem__(),key为test_getitem的键
    # def __getitem__(self, key):
    #     num2 = self.num1 + key
    #     return num2

test = test_getitem()
print(test[100])    # TypeError: 'test_getitem' object does not support indexing

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYwPMoQv' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片