面向对象编程(英语:Object-oriented programming,缩写:OOP)是一种编程理念,这种编程理念更符合我们人的逻辑思维。使用面向对象编程可以提高我们的开发速度和代码的重用率。面向对象的开发非常适合大型程序开发,开发速度和后期维护都比过程化开发要好很多。
面对对象内置了许多魔术方法,吃透一些常用的魔术方法是每一个程序员所必需的。下面我们介绍一些常用的魔术方法。
__init__
:__init__
在创建对象的时候自动执行,在__init__
中可以做一些初始化操作。创建对象需要的参数要在__init__
中设置。
class People():
def __init__(self,age): # 需要传的参数在__init__中定义
self.name = "大黄" # 初始化name值
self.age = age
p = People(18) # 实例化对象
print(p.name) # 大黄
print(p.age) # 18
__new__
:__new__
在实例化对象时触发,至少一个cls接收当前类,必须返回一个实例对象。实例化对象是Object类底层实现,其他类继承了Object的__new__
方法才能实现实例化对象,先触发__new__
方法才会触发__init__
方法,__new__
方法是是实例化一个对象,而__init__
方法是对这个对象进行初始化。该方法可用与单例模式中创建对象。
查看__new__
方法触发的时机:
class People():
def __new__(cls, *args, **kwargs):
print("------__new__------")
return super().__new__(cls) # 继承父类创建实例化对象
def __init__(self):
print("------__init__------")
p = People()
print(p) # 打印对象时,会自动触发__str__方法,打印对象名引用的内存地址
使用__new__
方法实现单例模式
class Sun():
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance: # 如何没有创建过实例对象,创建
cls._instance = super().__new__(cls)
return cls._instance # 返回实例对象
s1 = Sun()
s2 = Sun()
print(s1 is s2)
print(id(s1),id(s2))
可以看到两个实例对象的内存地址是一样的。
__del__
:__new__
方法是在实例化对象时执行,__init__
方法是在初始化实例对象时执行,__del__
方法则是在程序结束时执行,即对象销毁时执行,因此我们可以在对象销毁时做一些操作,程序会自动调用该方法,不需要手动调用。
查看__del__
触发时机:
class People():
def __init__(self,name):
self.name = name
print("{}来了".format(self.name))
def __del__(self):
print("{}走了".format(self.name))
p = People("大黄")
print(p)
__str__
:打印对象时会触发,通常用于快捷操作,默认情况下会打印对象名引用的内存地址,类似上图的<__main__
.People object at 0×000000000253D940>,可以通过重写__str__
方法打印我们需要的结果:
class People():
def __init__(self,name):
self.name = name
print("{}来了".format(self.name))
def __str__(self):
return "当前实例化的对象是:{}".format(self.name)
def __del__(self):
print("{}走了".format(self.name))
p = People("大黄")
print(p)
__repr__
:__repr__
方法改变对象的字符串显示,此方法是__str__
方法的备胎,如果找不到__str__
就会找__repr__
方法。%r默认调用__repr__
方法,如果是字符串会默认加上“”,%s默认调用__str__
方法:
class People():
def __init__(self,name):
self.name = name
print("{}来了".format(self.name))
def __str__(self):
return super().__str__()
def __repr__(self):
return "当前实例化的对象是:{}".format(self.name)
def __del__(self):
print("{}走了".format(self.name))
p = People("大黄")
print(p)
class People():
def __init__(self,name,age):
self.name = name
self.age = age
print("{}来了".format(self.name))
def __str__(self):
return "当前实例化的对象名字是:{}".format(self.name)
def __repr__(self):
return "当前实例化的对象年龄是:{}".format(self.age)
def __del__(self):
print("{}走了".format(self.name))
p = People("大黄",18)
print("%s"%p) # %s调用__str__方法
print("%r"%p) # %r调用__repr__方法
__call__
:__call__
可以让类的实例具有类似于函数的行为,进一步模糊了函数和对象之间的概念。
class People():
def __call__(self, *args, **kwargs):
print("------__call__------")
p = People()
p()
__eq__
:is比较两个对象的id是否相等,即是否指向同一个内存地址。==默认调用对象的__eq__
方法,__eq__
方法默认比较对象的id,即在不复写__eq__
方法的时候is和= =的结果是一样的:
class People(object):
def __init__(self):
super(People,self).__init__()
p1 = People()
p2 = People()
print(p1 is p2) # False
print(p1 == p2) # False
但一般情况下我们只需要对象的内容相同就可以认为其相等了,因此我们常常会去复写__eq__
方法:
class People(object):
def __init__(self):
super(People,self).__init__()
def __eq__(self, other):
return self.__dict__==other.__dict__
p1 = People()
p2 = People()
print(p1 is p2) # False
print(p1 == p2) # True
__hash__
:在 python 中 set 集合要求数据类型是可哈希的,因为 set 集合会默认调用对象的 __hash__
函数进行快速查询,如果找到了则调用对象的__eq__
判断两个是是否相同,如果相同则不添加,从而保证数据的唯一性。dict 数据结构的 key也必须是可哈希的,因为dict 是无序的因此通过 key 的 hash 算法来快速查询。
哈希集合就是很多个桶,但每个桶里只能放一个球,__hash__
函数作用就是找到桶的位置,到底是几号桶。 __eq__
方法作用就是当桶里有一个球了,但又来了一个球,他声称他也应该装进这个桶里(__hash__
函数给他说了桶的位置),双方僵持不下,那就得用__eq__
函数来判断这两个球是不是相等(equal),如果判断是相等的,那么后来的球就不应该放进桶里,哈希维持现状。如果只定义了__eq__
,不定义__hash__
,就找不到桶(默认为None),就会报错:
class People(object):
def __init__(self,name):
self.name = name
super(People,self).__init__()
def __eq__(self, other):
return self.__dict__==other.__dict__
p1 = People("大黄")
p2 = People("小白")
p3 = People("老黑")
s = {p1,p2,p3}
print(s)
定义__hash__
class People(object):
def __init__(self,name):
self.name = name
super(People,self).__init__()
def __eq__(self, other):
return self.__dict__==other.__dict__
def __hash__(self):
return super(People,self).__hash__()
p1 = People("大黄")
p2 = People("小白")
p3 = People("老黑")
s = {p1,p2,p3}
print(s)
hash()函数默认调用__hash__
方法,Hash值是对象id的1/16:
__slots__
:限制实例属性的创建:
class People(object):
def __init__(self):
super(People,self).__init__()
def __str__(self):
return repr(self.__dict__)
p = People()
p.name = "大黄"
p.age = 18
p.gender = "男"
print(p) # {'name': '大黄', 'age': 18, 'gender': '男'}
如果我们想让使用者只能创建“name”和“age”这两个属性,可以使用__slots__
:
class People(object):
__slots__ = ("name","age")
def __init__(self):
super(People,self).__init__()
def __str__(self):
return repr(self.__dict__)
p = People()
p.name = "大黄"
p.age = 18
p.gender = "男"
print(p)
报错