码迷,mamicode.com
首页 > 编程语言 > 详细

python基础===成员访问__len__()和__getitem__()

时间:2018-04-26 01:23:05      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:style   长度   asd   sel   soft   efault   取值   top   运算   

class A:

    def __init__(self,*args):
        self.name = arg
        pass

    def __len__(self):
        return len(self.name)


a = A("32","asda",435)
print(len(a)) 
# 3

返回对象实例的“长度”

 

 

凡是在类中定义了这个__getitem__ 方法,那么它的实例对象(假定为p),可以像这样p[key] 取值,当实例对象做p[key] 运算时,会调用类中的方法__getitem__。

一般如果想使用索引访问元素时,就可以在类中定义这个方法(__getitem__(self, key) )。

class DataBase:
    ‘‘‘Python 3 中的类‘‘‘

    def __init__(self, id, address):
        ‘‘‘初始化方法‘‘‘
        self.id = id
        self.address = address
        self.d = {self.id: 1,
                  self.address: "192.168.1.1",
                  }

    def __getitem__(self, key):
        # return self.__dict__.get(key, "100")
        return self.d.get(key, "default")
       

data = DataBase(1, "192.168.2.11")
print(data["hi"])
print(data[data.id])

 

 

 

 

 

参考资料:

https://blog.csdn.net/u013061183/article/details/74773196

https://zhuanlan.zhihu.com/p/27661382

 

python基础===成员访问__len__()和__getitem__()

标签:style   长度   asd   sel   soft   efault   取值   top   运算   

原文地址:https://www.cnblogs.com/botoo/p/8947516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!