您的位置:首页 > 其它

魔法方法——构造和析构__init__和__new__

2017-12-26 22:56 323 查看
读书笔记:









代码:

# -*- coding: gbk -*-
class FileObject():
def __init__(self,filename = "sample.txt"):
#读写模式打开一个文件
self.new_file = open(filename,"r+"):

def __del__(self):
self.new_file.close()
del self.new_file




class C2F(float):
#摄氏度转化为华氏温度
def __new__(cls,arg = 0.0):
return float.__new__(cls,arg * 1.8 +32)
print(C2F(33.3))


请比较代码:

>>> str.__new__(str,"8999")
'8999'
>>> float.__new__(float,9*1.8+32)
48.2




我的代码:

class Nint(int):
def __new__(cls,arg = 0):
if isinstance(arg,str):#若arg是str类型
tot = 0
for x in arg:
tot += ord(x)
arg = tot

return int.__new__(cls,arg)

print(int.__new__(int,3.5))
print(Nint(3.5))
print(Nint("zss"))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: