需要注意的是,如果类不定义__call__方法直接去调用,会报错
Traceback (most recent call last):
File "C:\Python-Project\Test\test.py", line 2374, in <module>
a(1, 2, b='Elaine')
TypeError: 'CallClass' object is not callable
2.Python中的__getitem__方法
在python中,如果在类的实例化后面加上中括号,相当于调用该实例的__getitem__方法,如果类没有定义该方法,会报错TypeError: ‘xxxxxx’ object is not subscriptable。
这是Python中的特殊方法,用于实现对象的索引操作,使对象能够像序列(如列表或元组)一样通过索引访问其元素。该方法被称为魔法方法,这个方法返回所给键对应的值。当对象是序列时,键是整数。当对象是映射时 (字典),键是任意值,在定义类时,如果希望能按照键取类的值,则需要定义__getitem__方法
以下是一个简单的示例:
class GetitemClass:
def \_\_init\_\_(self):
self.data = [1, 2, 3, 4, 5, 6]
def \_\_getitem\_\_(self, index):
return self.data[index]
if __name__ == '\_\_main\_\_':
a = GetitemClass()
print(a[2])
>>>输出:3
在这个例子中,创建了一个GetitemClass类,该类实现了__getitem__方法,允许通过索引访问其内部’data‘列表。当通过a[2]调用实例时,实际上调用了a.getitem(2),返回索引为2的元素。
这个方法的实现允许使用常见的序列访问方式,例如切片操作:
class GetitemClass:
def \_\_init\_\_(self):
self.data = [1, 2, 3, 4, 5, 6]
def \_\_getitem\_\_(self, index):
return self.data[index]
if __name__ == '\_\_main\_\_':
a = GetitemClass()
print(a[1:4])
>>>输出:[2, 3, 4]
类对象还可以像字典对象那样根据key取值(dict[‘key’]),如类对象Object[‘key’],系统会自动调用__getitem__方法,然后执行该方法定义的操作。
class GetitemClass:
def \_\_init\_\_(self):
self.data = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
def \_\_getitem\_\_(self, item):
data = self.data.get(item, '')
if data:
return data
raise Exception('关键字不存在')
if __name__ == '\_\_main\_\_':
a = GetitemClass()
print(a['key2'])
>>>输出:value2
3.一些其他相关的特殊方法
3.1 如果想使对象支持对元素赋值的操作,可以实现__setitem__方法。
class GetitemClass:
def \_\_init\_\_(self):
self.data = [1, 2, 3, 4, 5, 6]
def \_\_getitem\_\_(self, index):
return self.data[index]
def \_\_setitem\_\_(self, index, value):
self.data[index] = value
if __name__ == '\_\_main\_\_':
a = GetitemClass()
print(a[2])
a[2] = 10
print(a[2])
>>>输出:
3
10
3.2 如果希望对象表现得像一个序列,可以实现__len__方法返回对象长度