041魔法方法:构造和析构

魔法方法:总是被双下划线包围,例如:__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

posted @ 2015-10-18 07:11  淡蓝色的天空很美  阅读(413)  评论(0编辑  收藏  举报