Python学习笔记二十——小甲鱼第四十、四十一讲
0、魔法方法左右两边都有双下划线
1、__new__
2、当实例对象需要有明确的初始化的时候,需要调用__init__
3、__init__方法的返回值一定是none,不能是其它
4、__new__方法主要返回一个实例对象,通常是参数cls这个类的实例化对象,当然也可以返回其它对象
5、当对象将要被销毁的时候,__del__就会被调用
0、
class fileobject:
def __init__(self,filename = 'a'):
self.new_file = open(filename, 'r+')
def __del__(self):
self.new_file.close()
del self.new_file
1、
class c2f(float):
def __new__(cls,arg = 0.0):
return float.__new__(cls,arg * 1.8 + 32)
运行结果
>>> print(c2f(12))
53.6
>>>
2、
SyntaxError: invalid syntax
>>> class nint(int):
def __new__(cls,arg = 0):
if isinstance(arg,str):
total = 0
for each in arg:
total += ord(each)
arg = total
return int.__new__(cls,arg)
运行结果
>>> print(nint('sdv'))
333
>>>