面向对象的类的特殊成员

1. __doc__

    表示类的描述信息
1
2
3
4
5
6
7
8
9
class Foo:
    """ 描述类信息,这是用于看片的神奇 """
    def func(self):
        pass
print Foo.__doc__
 
==============
 
描述类信息,这是用于看片的神奇

2. __module__ 和  __class__ 

 __module__ 表示当前操作的对象在哪个模块
   __class__     表示当前操作的对象的类是什么

3. __init__

构造方法,通过类创建对象时,自动触发执行。
1
2
3
4
5
6
7
8
9
class Foo:
 
    def__init__(self, name):
        self.name = name
        self.age = 18
 
 
obj = Foo('wupeiqi')
# 自动执行类中的 __init__ 方法

  

 4. __del__

析构方法,当对象在内存中被释放时,自动触发执行。

注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。

1
2
3
4
class Foo:
 
    def__del__(self):
        pass

5. __call__

  对象后面加括号,触发执行。
 
注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
1
2
3
4
5
6
7
8
class Foo:
 
    def__init__(self):
        passdef__call__(self*args, **kwargs):
        print'__call__'
 
obj = Foo() # 执行 __init__
obj()       # 执行 __call__

6. __dict__ 

  类或对象中的所有成员

  上文中我们知道:类的普通字段属于对象;类中的静态字段和方法等属于类,即:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Province:
 
    country = 'China'
    def__init__(self, name, count):
        self.name = name
        self.count = count
 
    def func(self*args, **kwargs):
        print'func'
 
# 获取类的成员,即:静态字段、方法...
print Province.__dict__
# 输出:
{'country''China''__module__''__main__''func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__'None}
 
# 获取 对象obj1 的成员
obj1 = Province('HeBei',10000)
print obj1.__dict__
# 输出:{'count': 10000, 'name': 'HeBei'}

7. __str__

如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
1
2
3
4
5
6
7
class Foo:
    def__str__(self):
        return'wupeiqi'
 
obj = Foo()
print obj
# 输出:wupeiqi

8、__getitem____setitem____delitem__

 用于索引操作,如字典。以上分别表示获取、设置、删除数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python
# -*- coding:utf-8 -*-
  
class Foo(object):
    def __getitem__(self, key):
        print '__getitem__',key
  
    def __setitem__(self, key, value):
        print '__setitem__',key,value
  
    def __delitem__(self, key):
        print '__delitem__',key
  
 
obj = Foo()
  
result = obj['k1']      # 自动触发执行 __getitem__
obj['k2'= 'wupeiqi'   # 自动触发执行 __setitem__
del obj['k1']           # 自动触发执行 __delitem__

9、__getslice__、__setslice__、__delslice__

该三个方法用于分片操作,如:列表      slice  : 切片 切割
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python
# -*- coding:utf-8 -*-
  
class Foo(object):
  
    def __getslice__(self, i, j):
        print '__getslice__',i,j
  
    def __setslice__(self, i, j, sequence):
        print '__setslice__',i,j
  
    def __delslice__(self, i, j):
        print '__delslice__',i,j
 
obj = Foo()
  
obj[-1:1]                   # 自动触发执行 __getslice__
obj[0:1= [11,22,33,44]    # 自动触发执行 __setslice__
del obj[0:2]                # 自动触发执行 __delslice__

10. __iter__

 
用于迭代器,之所以列表、字典、元组可以进行for循环,是因为类型内部定义了 __iter__
 
第一步:
1
2
3
4
5
6
7
8
9
class Foo(object):
    pass
 
obj = Foo()
 
for in obj:
    print i
     
# 报错:TypeError: 'Foo' object is not iterable  可迭代的

第二步:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Foo(object):
     
    def__iter__(self):
        pass
 
obj = Foo()
 
for in obj:
    print i
 
# 报错:TypeError: iter() returned non-iterator of type 'NoneType'

第三步:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Foo(object):
 
    def__init__(self, sq):
        self.sq = sq
 
    def__iter__(self):
        return iter(self.sq)
 
obj = Foo([11,22,33,44])
 
for in obj:
    print i

以上步骤可以看出,for循环迭代的其实是  iter([11,22,33,44]) ,所以执行流程可以变更为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python
# -*- coding:utf-8 -*-
  
obj = iter([11,22,33,44])
  
for in obj:
    print i
 
 
For循环语法内部
#!/usr/bin/env python
# -*- coding:utf-8 -*-
obj = iter([11,22,33,44])
 
while True:
    val = obj.next()
    print val

  

 11. __new__ 和 __metaclass__

1
<span style="font-family: 'Microsoft YaHei';"><strong>阅读以下代码:</strong></span>
1
2
3
4
5
6
class Foo(object):
  
    def __init__(self):
        pass
  
obj = Foo()   # obj是通过Foo类实例化的对象
 
上述代码中,obj 是通过 Foo 类实例化的对象,其实,不仅 obj 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象。
 
如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。
 
1
2
print type(obj) # 输出:<class '__main__.Foo'>     表示,obj 对象由Foo类创建
print type(Foo) # 输出:<type 'type'>              表示,Foo类对象由 type 类创建

所以,obj对象是Foo类的一个实例Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。

那么,创建类就可以有两种方式:
 
a). 普通方式
 
1
2
3
4
class Foo(object):
  
    def func(self):
        print 'hello wupeiqi'
 
b).特殊方式(type类的构造函数)
 
1
2
3
4
5
6
7
def func(self):
    print 'hello wupeiqi'
  
Foo = type('Foo',(object,), {'func': func})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员
 
  ==》 类 是由 type 类实例化产生

 

原文地址:https://www.cnblogs.com/triple-y/p/9545379.html