一、 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)
二、__call__(),__str__(),__del__(),反射
这几个在之前的面向对象2里有总结:
https://blog.csdn.net/weixin_40406241/article/details/89403150#t15
三、__setattr__(),__delattr__(),__getattr__()
class Demo(object):
def __init__(self,name):
self.name = name
def __getattr__(self, item):
print('这个对象想获取一个它没有的属性>>>:',item)
def __setattr__(self, key, value):
print(key, value)
# 这里一定要继承父类,我们打印相当于重写了这个方法
super().__setattr__(key, value)
def __delattr__(self, item):
print('----> from delattr')
# del self.item # 无限递归了
self.__dict__.pop(item)
obj = Demo('jason') # self.name='jason',一旦有 对象.属性=值 的代码,就会触发__setattr__
obj.name = 'egon' # 触发__setattr__
obj.password = '123' # 触发__setattr__
print(obj.name)
print(obj.yyy) # obj对象只有name属性,没有yyy属性,这时会触发__getattr__执行
# __delattr__删除属性的时候会触发
del obj.password
print(obj.__dict__)
四、@property
class Goods:
def __init__(self):
# 原价
self.original_price = 100
# 折扣
self.discount = 0.8
@property # 将方法伪装成属性
def price(self):
# 实际价格 = 原价 * 折扣
new_price = self.original_price * self.discount
return new_price
@price.setter # 提供设置修改原价的方法
def price(self, value):
self.original_price = value
@price.deleter # 提供删除属性的方法
def price(self):
del self.original_price
obj = Goods()
obj.price # 获取商品价格
obj.price = 200 # 修改商品原价
print(obj.price)
del obj.price # 删除商品原价
五、__doc__
注释信息
该属性无法继承给子类
class Foo:
'''我是描述信息'''
pass
print(Foo.__doc__)
'''
结果:
我是描述信息
'''
六、__next__,__iter__
实现迭代器
可迭代对象.__iter__():将其变成迭代器对象
迭代器对象.__next__():取值
七、__module__和__class__
__module__ 表示当前操作的对象在那个模块
__class__ 表示当前操作的对象的类是什么
八、__new__
构造方法包括创建对象和初始化对象,在python当中,分为两步执行:先执行__new__方法,然后执行__init__方法;
__init__是当实例对象创建完成后被调用的,然后设置对象属性的一些初始值。
__new__是在实例创建之前被调用的,因为它的任务就是创建实例然后返回该实例,是个静态方法。
__new__在__init__之前被调用,__new__的返回值(实例)将传递给__init__方法的第一个参数,然后__init__给这个实例设置一些参数。
__new__
必须要有返回值,返回实例化出来的实例,这点在自己实现__new__
时要特别注意,可以return父类__new__
出来的实例,或者直接是object的__new__
出来的实例
class A:
def __init__(self):
print('__init__的地址:', self)
def __new__(cls, *args, **kwargs):
print('__new__的id:', id(cls))
res = object.__new__(cls)
print('__new__的地址', res)
return res
print('__init__的id:',id(A))
a = A()
'''
__init__的id: 86956443592
__new__的id: 86956443592
__new__的地址 <__main__.A object at 0x000000143F76C358>
__init__的地址: <__main__.A object at 0x000000143F76C358>
'''
类一旦重写__new__方法,该类的实例化由__new__来控制,通过重写此方法,可以实现单例模式:
__new__返回什么对象,就去调用对应的对象的__init__方法
九、__getitem__,__setitem__,__delitem
- 对象['xx'] 取值,会触发__getitem__()
- 对象['xx'] =10 设置值,会触发__setitem__()
- del 对象['触发'],会触发__delitem__
十、 with一个对象,自动触发__enter__方法
上下文管理协议,就是咱们打开文件时常用的一种方法:with
__enter__(self):当with开始运行的时候触发此方法的运行
__exit__(self, exc_type, exc_val, exc_tb):当with运行结束之后触发此方法的运行
class Foo(object):
def __init__(self):
pass
def __enter__(self):
print("__enter__")
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__")
obj = Foo()
with obj:
print("xxx")
# 结果
"""
__enter__
xxx
__exit__
"""