博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
041魔法方法:构造和析构
阅读量:4313 次
发布时间:2019-06-06

本文共 1868 字,大约阅读时间需要 6 分钟。

魔法方法:总是被双下划线包围,例如:__init__

        是面向对象的python的一切。
    魔力体现:总能够在适当的时候被调用
1. __init__(self[,...]):构造
   此函数的返回值一定是None
>>> class Rectangle:
...     def __init__(self,x,y):
...         self.x = x
...         self.y = y
...     def getPeri(self):
...         return (self.x+self.y) * 2
...     def getArea(self):
...         return  self.x * self.y
...
>>> rect = Rectangle(3,4)
>>> rect.getPeri()
14
>>> rect.getArea()
12
>>> class A:
...     def __init__(self):
...         return "A"
...
>>> a = A()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: __init__() should return None
2. __new__(cls[,...]):构造
   对象实例化时调用的第一个方法
   如果有额外的参数就传给__init__()
   要返回一个实例对象,一般是class对象,也可以是其他的对象
   一般不需要重写,但是有一种情况需要重写:当继承一个不可变类型时,但又想改变它
   如:>>> class CapStr(str):
       ...     def __new__(cls,string):
       ...         string = string.upper()
       ...         return str.__new__(cls,string)
       ...
       >>> a = CapStr("I love YOU")
       >>> a
       'I LOVE YOU'
3. __del__(self):析构
   垃圾回收机制
   当对象的所有引用都被del了就会调用__del__
   如:>>> class C:
       ...     def __init__(self):
       ...         print("init.....")
       ...     def __del__(self):
       ...         print("del.....")
       ...
       >>> c1 = C()
       init.....
       >>> c2 = c1
       >>> c3 = c2
       >>> del c3
       >>> del c2
       >>> del c1
       del.....
练习:
1. 避免文件打开忘记关闭,在删除对象时文件自动关闭
>>> class FileObject:
...     def __init__(self,filename='file.txt'):
...         self.new_file = open(filename,'r+')
...     def __def__(self):
...         self.new_file.close()
...         del self.new_file
...
2. 定义一个类,实现摄氏度到华氏度转换
   华氏度 = 摄氏度*1.8 + 32
   >>> class C2F(float):
   ...     def __new__(cls,arg=0.0):
   ...         return float.__new__(cls,arg*1.8 + 32)
   ...
3. 定义一个继承于int类型,并实现一个特殊功能:
   当传入的参数是字符串的时候,返回该字符串中所有字符的ASCII码的和
   用ord()获得一个字符的ASCII码值
   >>> 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(123))
   123
   >>> print(Nint(1.5))
   1
   >>> print(Nint('A'))
   65
   >>> print(Nint('Aa'))
   162

转载于:https://www.cnblogs.com/wangjiaxing/p/4888829.html

你可能感兴趣的文章
MySQL innert join、left join、right join等理解
查看>>
sdc时序约束
查看>>
NoC片上网络
查看>>
开源SoC整理
查看>>
【2020-3-21】Mac安装Homebrew慢,解决办法
查看>>
influxdb 命令行输出时间为 yyyy-MM-dd HH:mm:ss(年月日时分秒)的方法
查看>>
已知子网掩码,确定ip地址范围
查看>>
判断时间或者数字是否连续
查看>>
docker-daemon.json各配置详解
查看>>
Docker(一)使用阿里云容器镜像服务
查看>>
Docker(三) 构建镜像
查看>>
FFmpeg 新旧版本编码 API 的区别
查看>>
RecyclerView 源码深入解析——绘制流程、缓存机制、动画等
查看>>
Android 面试题整理总结(一)Java 基础
查看>>
Android 面试题整理总结(二)Java 集合
查看>>
学习笔记_vnpy实战培训day02
查看>>
学习笔记_vnpy实战培训day03
查看>>
VNPY- VnTrader基本使用
查看>>
VNPY - CTA策略模块策略开发
查看>>
VNPY - 事件引擎
查看>>