python中一些"魔法""方法

2017-10-31  本文已影响0人  Pello_Luo

1. __new __ 与 __init __

__ new __:通过对class创建实例对象时被调用,返回当前实例
__init __:创建完成对象后被调用,对类作初始化,无返回值,类似于c#构造方法

__ new __注意点:
  1. __ new __ 只能用于继承自object新式定义类才有
  2. __ new __ 必须有返回可以是return父类__ new__出来的实例,或者直接是object的 __ new__出来的实例且至少有一个形参cls
  3. 若 __new __没有正确返回当前类cls的实例,那 __ init __是不会被调用的,即使是父类的实例也不行
  4. 在类中,如果 __ new__和 __ init __同时存在,会优先调用 __ new __
优先调用 __ new __, 自动屏蔽 __ init __如:
 class test(object):
     def __new__(self):
            print "new"
    def __init__(self):
            print "init" 
 test1 = test()
结果:    new
__ init __不会被调用的情况,如:
<class '__main__.B'>
>>> class A(object):
...     def __new__(Class):
...             object = super(A,Class).__new__(Class)
...             print "in New"
...             return object
...     def __init__(self):
...             print "in init"
... 
>>> A()
in New
in init
<__main__.A object at 0x7fa8bc622d90>
>>> class A(object):
...     def __new__(cls):
...             print "in New"
...             return cls   #未返回对象
...     def __init__(self):
...             print "in init"
... 
>>> a = A()      
in New

2. __ str __ :打印对象信息

1.该内置函数return的数据为字符串,若非字符串需要str()转成字符串
2.只能有self这个形参

#!/usr/bin/env python                                                                                                                                                                                 
class test(object):  
    def __init__(self):  
        print "init: this is init test"  
    def __str__(self):  
        return "str: this is str test "  
if __name__ == "__main__":  
    st=strtest()  
    print st 

3.__ repr __

4. __ all __

5. __ del __

6.__ dict __

__ dict __是一个字典,键为属性名,值为属性值

#定义一个类
In [1]: class A():
             #实例属性
             y=2 
             #类属性
             def __init__(self):
                 self.x=1   
In [2]: a=A()
In [3]: print a.__dict__ #打印实例属性
{'x': 1}
In [4]: a.__dict__={}   #清空实例属性
In [5]: print a.y
2
In [6]: print a.x    #清空后报错
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-98883728128d> in <module>()
----> 1 print a.x
AttributeError: A instance has no attribute 'x'
In [7]: print A.__dict__  #打印类属性
{'y': 2, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x0000000004F4CC18>}
In [8]: A.__dict__={}    #清空类属性
In [9]: print A.y  #清空后报错
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-e07ddb174d62> in <module>()
----> 1 print A.y
AttributeError: class A has no attribute 'y'
上一篇 下一篇

猜你喜欢

热点阅读