魔法方法——构造和析构__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"))
相关文章推荐
- 魔法方法:构造和析构 - 零基础入门学习Python041
- Python类方法__init__和__del__构造、析构过程分析
- 零基础入门学习Python(21):魔法方法(1)构造和析构
- 041魔法方法:构造和析构
- OC中new方法与alloc+init及构造方法
- python中__init__()、__new__()、__call__()、__del__()几个魔法方法的用法
- 鱼c笔记——Python魔法方法一:构造和析构
- Python类方法__init__和__del__构造、析构过程分析
- swift自学笔记(六)(构造方法、析构方法)
- -PHP面向对象(OOP)编程入门-8.构造方法__construct()与析构方法__destruct()
- 陈力:传智播客古代 珍宝币 泡泡龙游戏开发第32讲:PHP 构造方法、析构方法
- 继承类的构造和析构方法
- PHP魔术方法之构造方法__construct与析构方法__destruct
- Java构造方法和析构方法
- Python中的__init__方法与__new__方法的区别
- 构造方法与析构方法
- new方法和init方法的区别
- 浅谈python中的__init__、__new__和__call__方法
- php面向对象的构造方法与析构方法
- Python中__new__与__init__方法的区别详解