类中的特殊成员

一些类中的特殊成员:

 

创建一个类:

  1. class Foo:  
  2.     """ 
  3.    这是一个注释 
  4.    """  
  5.     name=""  
  6.     def f(self):  
  7.         pass  

查看他的所有成员有哪些:

  1. import inspect  
  2. print(inspect.getmembers(Foo))  

结果如下:

[('__class__', <class 'type'>),

('__delattr__', <slot wrapper '__delattr__' of 'object' objects>),

('__dict__',

mappingproxy({'__dict__': <attribute '__dict__' of 'Foo' objects>,

'__doc__': ' 这是一个注释 ',

'__module__': '__main__',

'__weakref__': <attribute '__weakref__' of 'Foo' objects>,

'f': <function Foo.f at 0x048408A0>,

'name': ''})),

('__dir__', <method '__dir__' of 'object' objects>),

('__doc__', ' 这是一个注释 '),

('__eq__', <slot wrapper '__eq__' of 'object' objects>),

('__format__', <method '__format__' of 'object' objects>),

('__ge__', <slot wrapper '__ge__' of 'object' objects>),

('__getattribute__', <slot wrapper '__getattribute__' of 'object' objects>),

('__gt__', <slot wrapper '__gt__' of 'object' objects>),

('__hash__', <slot wrapper '__hash__' of 'object' objects>),

('__init__', <slot wrapper '__init__' of 'object' objects>),

('__le__', <slot wrapper '__le__' of 'object' objects>),

('__lt__', <slot wrapper '__lt__' of 'object' objects>),

('__module__', '__main__'),

('__ne__', <slot wrapper '__ne__' of 'object' objects>),

('__new__', <built-in method __new__ of type object at 0x69C5BAD0>),

('__reduce__', <method '__reduce__' of 'object' objects>),

('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>),

('__repr__', <slot wrapper '__repr__' of 'object' objects>),

('__setattr__', <slot wrapper '__setattr__' of 'object' objects>),

('__sizeof__', <method '__sizeof__' of 'object' objects>),

('__str__', <slot wrapper '__str__' of 'object' objects>),

('__subclasshook__',

<built-in method __subclasshook__ of type object at 0x04B725B8>),

('__weakref__', <attribute '__weakref__' of 'Foo' objects>),

('f', <function Foo.f at 0x048408A0>),

('name', '')]

区分其中的字段和方法去看:

  1. instance = []  
  2. function = []  
  3. for i in dir(Foo):  
  4.     if callable(getattr(Foo, i)):  
  5.         function.append(i)  
  6.     else:  
  7.         instance.append(i)  
  8. print(instance)  
  9. print(function)  
  10.     
  11. # ['__dict__', '__doc__', '__module__', '__weakref__', 'name']  
  12. # ['__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'f'] 

我们看到有一下这些字段:

['__dict__', '__doc__', '__module__', '__weakref__', 'name']

一个一个看:

__dict__

In [27]: Foo.__dict__

Out[27]:

mappingproxy({'__dict__': <attribute '__dict__' of 'Foo' objects>,

'__doc__': ' 这是一个注释 ',

'__module__': '__main__',

'__weakref__': <attribute '__weakref__' of 'Foo' objects>,

'f': <function __main__.Foo.f>,

'name': ''})

是用来存储对象属性的一个字典,其键为属性名,值为属性的值

__doc__

In [31]: Foo.__doc__

Out[31]: ' 这是一个注释 '

表示类的描述信息

__module__

In [32]: Foo.__module__

Out[32]: '__main__'

表示从哪个模块导入的

__weakref__

看这个就好了: 其实就是没啥用

https://stackoverflow.com/questions/36787603/what-exactly-is-weakref-in-python

'name'

其实就是我们定义的静态字段

接下来是方法

['__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'f']

/////////

__func__这样的都是内部方法

 

 

 

 

 

 

__init__ 构造方法:

def __init__(self):

super().__init__()

 

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

def __call__(self, *args, **kwargs):
pass

 

`模拟一个list

  1. # coding=utf-8  
  2. class Foo:  
  3.     """模拟一个list"""  
  4.     def  __getitem__(self, item):  
  5.     
  6.         if type(item)==int:  
  7.             print(item)  
  8.         else:  
  9.             start=item.start  
  10.             stop=item.stop  
  11.             step=item.step  
  12.             print(start)  
  13.     def  __setitem__(self, key, value):  
  14.         print(key,value)  
  15.     def __delitem__(self, key):  
  16.         print(key)  
  17.     
  18. f=Foo()  
  19. f[1]  
  20. f[5:3:5]  
  21. del f[9]  

 

 

 

 __iter__ 

用于迭代器,之所以列表、字典、元组可以进行for循环,是因为类型内部定义了 __iter__ 

In [46]: [1,2,3].__iter__()

Out[46]: <list_iterator at 0x4b7e6b0>

 

In [47]: iter([1,2,3])

Out[47]: <list_iterator at 0x4b7e790>

 

 

__next__方法 :next(obj)

自动调用obj的iter方法

 

__new__  __metaclass__看上一个博客

 

利用__new__方法可以创建单例模式

原文地址:https://www.cnblogs.com/twotigers/p/7779501.html