Python类的特殊成员方法

来源:互联网 发布:网络盒子怎样双清 编辑:程序博客网 时间:2024/06/06 01:36

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

2. __module__ 和  __class__ 

  __module__ 表示当前操作的对象所在的那个模块

  __class__     表示当前操作的对象的类是什么

 lib/aa.py
  1. class C:
  2. def __init__(self):
  3. self.name = 'wupeiqi'

 index.py
  1. from lib.aa import C
  2. obj = C()
  3. print obj.__module__ # 输出 lib.aa,即:输出模块
  4. print obj.__class__ # 输出 lib.aa.C,即:输出类
  5. index.py

3. __init__ 构造方法,通过类创建对象时,自动触发执行。


4.__del__

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

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

 

5. __call__ 对象后面加括号,触发执行。

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;

而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

  1. class Foo:
  2. def __init__(self):
  3. print('执行 __init__ 方法')
  4. pass
  5. def __call__(self, *args, **kwargs):
  6. print ('执行 __call__ 方法')
  7. pass
  8. obj = Foo() # 执行 __init__
  9. obj() # 执行 __call__
输出结果:
  1. 执行 __init__ 方法
  2. 执行 __call__ 方法

6. __dict__ 查看类或对象中的所有成员   

  1. class Province:
  2. country = 'China'
  3. def __init__(self, name, count):
  4. self.name = name
  5. self.count = count
  6. def func(self, *args, **kwargs):
  7. print 'func'
  8. # 获取类的成员,即:静态字段、方法、
  9. print Province.__dict__
  10. # 输出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__':


7.__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。

  1. class Foo:
  2. def __str__(self):
  3. return 'FLY'
  4. obj = Foo()
  5. print (obj)
输出:
  1. FLY

8.__getitem__、__setitem__、__delitem__

  • 用于索引操作,如字典。以上分别表示获取、设置、删除数据

  1. class Foo(object):
  2. def __getitem__(self, key):
  3. print('__getitem__',key)
  4. def __setitem__(self, key, value):
  5. print('__setitem__',key,value)
  6. def __delitem__(self, key):
  7. print('__delitem__',key)
  8. obj = Foo()
  9. result = obj['k1'] # 自动触发执行 __getitem__
  10. obj['k2'] = 'alex' # 自动触发执行 __setitem__
  11. del obj['k1']

输出结果:

  1. __getitem__ k1
  2. __setitem__ k2 alex
  3. __delitem__ k1

9. __new__ \ __metaclass__

  1. class Foo(object):
  2. def __init__(self, name):
  3. self.name = name
  4. obj = Foo("alex")
  5. print(obj)
  6. print(type(obj))
  7. print(type(Foo))

    上述代码中,obj 是通过 Foo 类实例化的对象,其实,不仅 obj 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象

    如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。

  1. print type(obj) # 输出:<class '__main__.Foo'> 表示,obj 对象由Foo类创建
  2. print type(Foo) # 输出:<type 'type'> 表示,Foo类对象由 type 类创建

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

    那么,创建类就可以有两种方式:

a). 普通方式

  1. class Foo(object):
  2. def func(self):
  3. print 'hello alex'

b). 特殊方式

  1. def func(self):
  2. print 'hello wupeiqi'
  3. Foo = type('Foo',(object,), {'func': func})
  4. #type第一个参数:类名
  5. #type第二个参数:当前类的基类
  6. #type第三个参数:类的成员

加上构造方法

  1. def func(self):
  2. print("Hello %s,%d岁生日快乐"%(self.name,self.age))
  3. def __init__(self,name,age):
  4. self.name = name
  5. self.age = age
  6. Foo = type('Foo',(object,),{'func':func,'__init__':__init__})
  7. f = Foo("FLY",26)
  8. f.func()
输出结果:
  1. Hello FLY,26岁生日快乐

So ,类 是由 type 类实例化产生

  • 那么问题来了,类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
  • 答:类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程。


 

  1. class MyType(type):
  2. def __init__(self,*args,**kwargs):
  3. print("Mytype __init__",*args,**kwargs)
  4. def __call__(self, *args, **kwargs):
  5. print("Mytype __call__", *args, **kwargs)
  6. obj = self.__new__(self)
  7. print("obj ",obj,*args, **kwargs)
  8. print(self)
  9. self.__init__(obj,*args, **kwargs)
  10. return obj
  11. def __new__(cls, *args, **kwargs):
  12. print("Mytype __new__",*args,**kwargs)
  13. return type.__new__(cls, *args, **kwargs)
  14. print('here...')
  15. class Foo(object,metaclass=MyType):
  16. def __init__(self,name):
  17. self.name = name
  18. print("Foo __init__")
  19. def __new__(cls, *args, **kwargs):
  20. print("Foo __new__",cls, *args, **kwargs)
  21. return object.__new__(cls)
  22. f = Foo("Alex")
  23. print("f",f)
  24. print("fname",f.name)
输出结果:
  1. here...
  2. Mytype __new__ Foo (<class 'object'>,) {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000000002C83730>, '__new__': <function Foo.__new__ at 0x0000000002C837B8>}
  3. Mytype __init__ Foo (<class 'object'>,) {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000000002C83730>, '__new__': <function Foo.__new__ at 0x0000000002C837B8>}
  4. Mytype __call__ Alex
  5. Foo __new__ <class '__main__.Foo'>
  6. obj <__main__.Foo object at 0x0000000002C86898> Alex
  7. <class '__main__.Foo'>
  8. Foo __init__
  9. f <__main__.Foo object at 0x0000000002C86898>
  10. fname Alex

类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__