类的特殊成员

该博客主要介绍了Python中的多种特殊方法,包括__call__、__int__、__str__、__add__等方法,还提到了__dict__方法可将对象封装内容以字典形式返回,以及__getitem__等方法,最后提及了metaclass元类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值