python3与python2其中的一个区别就是python3默认继承object这个类。
image
我们可以在object的源码中看到一大堆__ xxx __的方法,这些方法就是类的内置方法
这篇文章会记录其中一些常用的方法
class object:
""" The most base type """
def __delattr__(self, *args, **kwargs): # real signature unknown
""" Implement delattr(self, name). """
pass
def __dir__(self): # real signature unknown; restored from __doc__
"""
__dir__() -> list
default dir() implementation
"""
return []
.
.
.
1、 __ init __ 与 __ new __
__ new __ :在 __ init __ 触发前,自动触发,调用该类时,内部会通过__ new __产生一个新的对象
__ init __ :在调用类产生实例化对象时触发,通过产生的对象自动调用 __ init __()
class Demo(object):
# 条件: __new__: 在__init__触发前,自动触发。
def __new__(cls, *args, **kwargs):
print('此处是__new__方法的执行')
# python内部通过object调用内部的__new__实现产生一个空的对象 ---> 内存地址
return object.__new__(cls, *args, **kwargs)
# 条件: __init__: 在调用类时自动触发。
def __init__(self):
print('此处是__init__方法的执行')
2、__ getattr __ 与 __ getattribute __
__ getattr __ :在“对象.属性”获取属性时,若属性没有时触发。
__ getattribute __ :在 “对象.属性” 获取属性时,无论 "属性有没有" 都会触发。
# __getattr__: 在 “对象.属性” 获取属性时,若 “属性没有” 时触发。
# a = 1
def __getattr__(self, item):
print('此处是__getattr__方法的执行')
print(item)
# return 想要返回的值
return '送你一把大宝剑'
print(Demo().a) # 当存在a时打印1,当a不存在时打印"a",并返回"送你一把大宝剑"
# ===============================================================
# __getattribute__: 在 “对象.属性” 获取属性时,无论 "属性有没有" 都会触发。
def __getattribute__(self, item):
print(item, '<-----打印属性名字')
print(self.__dict__)
return self.__dict__[item]
# 注意: 此处不能通过 对象.属性,否则会产生递归调用,程序崩溃
# getattr: 内部调用了 ----> __getattribute__
return getattr(self, item)
# 注意: 只要__getattr__ 与 __getattribute__ 同时存在类的内部,只会触发__getattribute__。
3、__ setattr __
# 条件: 当 “对象.属性 = 属性值” , 添加或修改属性时触发
def __setattr__(self, key, value): # key---> 对象.属性名 value ---》 属性值
print('此处是__setattr__方法的执行')
print(key, value)
# 出现递归
# self.key = value
# print(self.__dict__)
# 此处是对 对象的名称空间 ---》 字典进行操作
self.__dict__[key] = value
4、 __ call __
# 条件: 在调用对象 “对象 + ()” 时触发。
def __call__(self, *args, **kwargs):
print('此处是__call__方法的执行')
# 调用对象时返回的值
return [1, 2, 3, 4, 5]
5、__ str __
# 条件: 在打印对象时触发。
# 注意: 该方法必须要有一个 “字符串” 返回值。
def __str__(self):
print('此处是__str__方法的执行')
return '111'
6、__ getitem __
# 在对象通过 “对象[key]” 获取属性时触发。
def __getitem__(self, item):
print('此处是__getitem__方法的执行')
print(item)
return self.__dict__[item]
7、 __ setitem __
# 在对象通过 “对象[key]=value值” 设置属性时触发。
def __setitem__(self, key, value):
print('此处是__setitem__方法的执行')
print(key, value)
# print(self.__dict__)
# self.key = value # {'key': value}
# print(self.__dict__)
self.__dict__[key] = value