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
Returns the "length" of the object instance
If this __getitem__ method is defined in the class, then its instance object (assumed to be p) can take the value of p[key] like this. When the instance object performs the p[key] operation, the method in the class will be called _ _getitem__.
Generally, if you want to use the index to access elements, you can define this method in the class (__getitem__(self, key) ).
class DataBase:
''' class in Python 3 '''
def __init__ (self, id, address):
''' initialization method '''
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])
References:
https://blog.csdn.net/u013061183/article/details/74773196
https://zhuanlan.zhihu.com/p/27661382