isinstance与issubclass:
class Bar:
pass
class Foo(Bar):
pass
print(issubclass(Foo,Bar)) Ture
obj=Foo()
print(isinstance(obj,Foo)) Ture
print(isinstance([1,2,3],list)) Ture
print(type(obj) is Foo) Ture
print(type([1,2,3]) is list) Ture
反射:通过字符串来反射/映射到对象/类的属性上
class People:
def __init__(self,name,age):
self.name=name
self.age=age
def run(self):
print('%s is running' %self.name)
obj=People('egon',18)
内置方法
__str__: 在对象被打印时自动触发,可以用来定义对象被打印时的输出信息
注意:必须返回一个字符串类型的值
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
# print('run..........')
return '<name:%s age:%s>' % (self.name, self.age)
obj1 = People('egon', 18)
print(obj1) # print(obj1.__str__())
obj2=list([1,2,3])
print(obj2)
__del__: 在对象被删除时先自动触发该方法,可以用来回收对象以外其他相关资源,比如系统资源
class Foo:
def __init__(self,x,filepath,encoding='utf-8'):
self.x=x
self.f=open(filepath,'rt',encoding=encoding)
def __del__(self):
print('run.....')
# 回收对象关联的其他资源
self.f.close()
obj=Foo(1,'a.txt')
# del obj
print('主===========>')
__call__: 在对象被调用时会自动触发该方法,可以用来???
class Foo:
def __init__(self,x,y):
self.x=x
self.y=y
def __call__(self, *args, **kwargs):
print(self,args,kwargs)
obj=Foo(1,2)
obj(1,2,a=3,b=4) #obj.__call__(obj,1,2,a=3,b=4)