---
title: "python 魔法方法(一）"
author: "rockkyle"
date: "2013-11-15T16:43:13Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2013-11-15T16:43:13Z"
id: 1973180
url: "https://rockkyle.iteye.com/blog/1973180"
---

一、\_\_init\_\_和\_\_del\__

\_\_init\_\_主要是实例初始化， \_\_del\_\_相当于析构器

```
#/usr/bin/env python
#-*- coding:utf-8 -*-
class test(object):
#实例初始化
        def __init__(self):
                print "call __init__"
#析构器
        def __del__(self):
                print "call __del__"
t=test()
```

 

```
call __init__
call __del__
```

 init在实例化的时候调用，del在对象销毁时自动调用，一般类中都默认带有\_\_del\_\_不需要自己声明

二、  \_\_new\_\_和\_\_init\__

**官网解释：**

**`If __new__()  returns an instance of cls, then the new instance’s __init__()`**

**`method will be invoked like __init__(self[, ...]), where self` `is` `the new instance`**

**`and` `the remaining arguments are the same as were passed to __new__().`**

**如果\_\_new\_\_()返回cls的实例，则新实例的\_\_init\_\_()方法会像\_\_init\_\_(self\[,...])调用,其中self是新实例，其他的参数和传给\_\_new\_\_()中的一样`If __new__() does not` `return` `an instance of cls, then the new instance’s __init__() method will not`**  `be invoked.`

如果 \_\_new\_\_()不返回实例，则\_\_init\_\_()不会被调用

`1、__new__ 是在__init__之前被调用的特殊方法，不返回实例`

```
class A(object):
        def __init__(self):
                print "call __init__"
        def __new__(self):
                print "call __new__"

a=A()——
```

 

```
call __new__
```

2、返回实例

```
class A(object):
        def __init__(self,x=0):
                print "call __init__"
                self.x=x
        def __new__(cls):
                print "call __new__"
#返回cls的实例
                return super(A,cls).__new__(cls)
a=A()
```

 

```
call __new__
call __init__
```

 2种方法刚好验证官网的解释`，另外__init__只是用来将传入的参数初始化给对象,__new__很少用到，除非你希望能够控制对象的创建。`

三、\_\_call\__

类中定义了\_\_call\__ ()方法，表明类可以作为方法被调用

```
class B(object):
#define __call__
        def __call__(self,x=0):
                print "call __call__()"
#value that the method returns
                return x
#instance
b=B()
#invoked as a method
b()
print b(1)
```

 

```
call __call__()
call __call__()
1
```

 可以看出作为方法调用时获得的返回值为\_\_call\_\_()中返回的值。

 

四、其他的一些基本的定制魔法方法

```
#/usr/bin/env python
#-*- coding:utf-8 -*-
#instance
class C(object):
#内建str()以及print语句
        def __str__(self):
                print "call __str__"
                return "class C __str__"
#内建repr()和操作符
        def __repr__(self):
                print "call __repr__"
                return "class C __repr__"
#内建unicode()
        def __unicode__(self):
                print "call __unicode__"
                return "call C __unicode__"
#内建bool()
        def __nozero__(self):
                print "call __nozeto__"

#内建len()
        def __len__(self):
                print "call __len__"
                return 1
c=C()
#首先 c 会调用__str__中的print
#print c 会答应__str__方法返回值
print c
#repr(c)的时候调用 __repr__方法中的print
#print repr(c)会打印__repr__方法的返回值
print repr(c)
#unicode(c)的时候调用 __unicode__方法中的print
#print unicode(c)会打印__unicode__方法的返回值
print unicode(c)
#len(c)的时候调用 __len__方法中的print
#print len(c)会打印__len__方法的返回值
print len(c)
#bool(c)的时候调用 __len__方法中的print
#print bool(c)如果len(c)为0则返回False，非0则为True
print bool(c)
```

 结果：

```
call __str__
class C __str__
call __repr__
class C __repr__
call __unicode__
call C __unicode__
call __len__
1
call __len__
True
```