Python——内置方法

内置方法

判断对象的类型

isintance(对象,类型)

判断是否是子类

issubclass(子类,父类)


__str__方法

会在对象被打印时自动触发,然后将返回值返回给print功能进行打印

1
2
3
4
5
6
7
8
9
10
11
class People:
def __init__(self,name,age):
self.name=name
self.age=age

def __str__(self):
return '<%s:%s>' %(self.name,self.age)

peo=People('ooc',18)
print(peo) #print(peo.__str__())
# <ooc:18>

__del__方法

会在对象被删除时自动触发执行,用来在对象被删除前回收系统资源

1
2
3
4
5
6
7
8
9
10
11
class Bar:
def __init__(self,x,y,filepath):
self.x=x
self.y=y
self.f=open(filepath,'r',encoding='utf-8')
def __del__(self):
# 写回收系统资源相关的代码
self.f.close()

obj=Bar(10,20)
del obj