python魔术方法:魔术方法是面向对象Python语言中的一切。它们是你可以自定义并添加“魔法”到类中的特殊方法。它们被双下划线环绕(比如init或lt)。
实例一、python实例化过程
首先调用new方法,返回一个Programer对象,然后把Programer对象交给init,由init对属性设置。
class Programer():
def __new__(cls,*args,**kwargs):
print('call __new__ method')
print(args)
return super(Programer,cls).__new__(cls)
def __init__(self,name,age):
print('call __init__ method')
self.name = name
self.age = age
if __name__ == '__main__':
programer = Programer('Albert',25)
print(programer.__dict__)
运行结果:
call __new__ method
('Albert', 25)
call __init__ method
{'name': 'Albert', 'age': 25}
实例二、类与运算符
class Programer(object):
def __init__(self,name,age):
self.name = name
if isinstance(age,int):
self.age = age
else:
raise Exception('age must be int')
def __eq__(self,other):
if isinstance(other,Programer): # 首先判断是否Programer对象
if self.age == other.age:
return True
else:
return False
else:
raise Exception('The type of object must be Programer')
def __add__(self,other):
if isinstance(other,Programer):
return self.age + other.age
else:
raise Exception('The type of object must be Programer')
if __name__ == '__main__':
p1 = Programer('Albert',25)
p2 = Programer('Bill',30)
print(p1==p2)
print(p1+p2)
运行结果:
False
55
实例三、类的展现
python里面的内建函数大部分都是由魔术方法支持的,如果想让类的对象使用python里面的内建方法,则需要定义相应的魔术方法。
class Programer(object):
def __init__(self,name,age):
self.name = name
if isinstance(age,int):
self.age = age
else:
raise Exception('age must be int')
def __str__(self):
return '%s is %s years old'%(self.name,self.age)
def __dir__(self):
return self.__dict__.keys()
if __name__ == '__main__':
p = Programer('Albert',25)
print(p)
print(dir(p))
运行结果:
Albert is 25 years old
['age', 'name']
实例四、类的属性控制
class Programer(object):
def __init__(self,name,age):
self.name = name
self.age = age
def __getattribute__(self,name):
# return getattr(self,name) # 会产生无限递归
return super(Programer,self).__getattribute__(name) # 调用父类的getattribute方法,不会产生无限递归
def __setattr__(self,name,value):
# setattr(self,name,value) # 会产生无限递归
self.__dict__[name] = value
if __name__ == '__main__':
p = Programer('Albert',25)
print(p.name)
运行结果:
Albert