一、isinstance(obj,cls)和issubclass(sub,super)
isinstance(obj,cls)检查是否obj是否是类 cls 的对象
class Foo(object): pass obj = Foo() isinstance(obj, Foo)
issubclass(sub, super)检查sub类是否是 super 类的派生类
class Foo(object): pass class Bar(Foo): pass issubclass(Bar, Foo)
二、反射
python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)
三、item系列
# item 系列 class Foo: # Dict def __init__(self, name): self.name = name def __getitem__(self, item): # item = 'name' print('getitem...') self.__dict__[item] print(item) def __setitem__(self, key, value): print('setitem...') print(key, value) self.__dict__[key] = value def __delitem__(self, key): print('delitem...') print(key) self.__dict__.pop(key) obj = Foo('egon') print(obj.__dict__) # 设置属性: obj['sex'] = 'male' print(obj.__dict__) print(obj.sex) # 删除属性: del obj['name'] print(obj.__dict__)
四、__str__
class People: def __init__(self, name, age): self.name = name self.age = age def __str__(self): # 打印对象时,自动触发,把返回的string类型的结果输出 return '<name:%s, age:%s>' % (self.name, self.age) obj = People('egon', 18) print(obj) # obj.__str__
五、__del__
class Open: def __init__(self, filename): print('open file...') self.filename = filename def __del__(self): print('回收操作系统资源:self.close()') f = Open('settings.py') del f # f.__del__() # 在不绑定__del__的情况下,python不会回收应用系统的资源f # 绑定__del__的情况下,python会在程序运行结束后,自动回收系统的资源