# --------- isinstance ------------
class Foo:
pass
obj = Foo()
print(isinstance(obj,Foo)) # 结果为True
# ---------- issubclass ------------
class Foo:
pass
class Bar(Foo):
pass
print(issubclass(Bar,Foo)) # 结果为True
# 内置方法 Item 系列
class Foo:
def __init__(self, name):
self.name = name
def __getitem__(self, item):
return self.__dict__.get(item)
def __setitem__(self, key, value):
self.__dict__[key] = value
def __delitem__(self, key):
del self.__dict__[key]
obj = Foo('kingforn')
print(obj.name) # 执行结果:kingforn
print(obj['name']) # 执行结果:kingforn
obj['sex'] = 'female'
print(obj.__dict__) # {'name': 'kingforn', 'sex': 'female'}
del obj['sex']
print(obj.__dict__) # {'name': 'kingforn'}
# __str__ 方法
d = dict({'name':'kingforn','age':18})
print(isinstance(d,dict)) # 执行结果为 True
print(d) # 执行结果为 {'name': 'kingforn', 'age': 18}
class Foo:
pass
d1 = Foo()
print(isinstance(d1,Foo)) # 执行结果为 True
print(d1) # 执行结果为 <__main__.Foo object at 0x00000206C52C4C18>
class People:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return '<name : %s , age : %s>' % (self.name, self.age)
d2 = People('alex', 18)
print(d2) # 执行结果为 <name : alex , age : 18>
__del__ 方法
class Open:
def __init__(self,filename):
print('open file ...............')
self.filename=filename
def __del__(self):
print('自动回收操作系统资源:self.close()')
f = Open('settings.py')
print('----- main ----------')
'''
执行结果为:
open file ...............
----- main ----------
自动回收操作系统资源:self.close()
'''