类的特殊成员

1.__call__方法

class Foo:
    def __call__(self, *args, **kwargs):
        print(58)
obj = Foo()
obj()    #对象后面加括号,触发__call__方法

2.__int__方法/__str__方法

class Foo:
    def __int__(self):
        return 12       #该方法必须返回整型
    def  __str__(self):
        return 'apple'  #该方法必须返回字符串
obj = Foo()
print(int(obj))    #__int__方法的触发方式
print(obj)         #__str__方法的触发方式
print(str(obj))    #__str__方法的另一种触发方式

3.__add__方法

class Foo:
    def __init__(self,n,a):
        self.name = n
        self.age = a
    def __add__(self, other):   #self接收第一个对象,other接收第二个对象
        return self.age + other.age
obj1 = Foo('alex',12)
obj2 = Foo('eric',21)
r = obj1 + obj2     #'obj1 + obj2'触发__add__方法
print(r)

4.__dict__方法:将对象中封装的所有内容以字典的形式返回

class Foo:
    def __init__(self,n,a):
        self.name = n
        self.age = a
obj = Foo('alex','15')
d = obj.__dict__   #__dict__方法的触发方式
print(d)

5.__getitem__/__setitem__/__delitem__方法

 1 class Foo:
 2     def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5     def __getitem__(self, item):
 6         if type(item) == int:    #索引触发时,item接收的是int型
 7              return item + 5
 8         else:                    #否则就是切片触发,item接收的是slice类型
 9             print(item.start,item.step,item.stop)
10     def __setitem__(self, key, value):
11         print(key,value)
12     def __delitem__(self,key):
13         print(key)
14 obj = Foo('alex',18)
15 print(obj[8])    #此处索引obj[8]触发__getitem__方法,8被传给了item
16 obj[1:3:2]       #此处切片触发的也是__getitem__方法。1,3,2分别被item.start,item.step,item.stop接收
17 obj[100] = 'dsf' #该句触发__setitem__方法,100被传给了key,'dsf'被传给了value
18 del obj[2]       #该句触发__delitem__方法,2被传给了key
19 '''注意:以上三种类似于列表的索引、切片/赋值/删除操作,但并没有实现这些功能,仅仅是一种触发方法的对应关系'''

6.__iter__方法

class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __iter__(self):   #iter方法的作用是生成一个迭代器
        return iter([11,12,13])
obj = Foo('alec',12)    #带有iter方法的对象是可迭代对象,例如obj就是这样的对象
for i in obj:           #for循环如果遇到的是可迭代对象,会先触发其iter方法拿到迭代器,然后用next方法遍历
    print(i)

7.metaclass

class mytype(type):
    def __call__(self, *args, **kwargs):
        print(125)
class Foo(object,metaclass=mytype):   #metaclass规定Foo是mytype的对象(默认情况下Foo是type的对象)
    pass
obj = Foo()    #obj是Foo的对象,Foo又是mytype的对象。python中对象是单向的
原文地址:https://www.cnblogs.com/Finance-IT-gao/p/10545934.html