1. 程式人生 > >類中的特殊成員

類中的特殊成員

__call__ 構造 hook 叠代器 ack start 信息 __str__ fun

一些類中的特殊成員:

創建一個類:

  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. # [‘__dict__‘, ‘__doc__‘, ‘__module__‘, ‘__weakref__‘, ‘name‘]
  11. # [‘__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. if type(item)==int:
  6. print(item)
  7. else:
  8. start=item.start
  9. stop=item.stop
  10. step=item.step
  11. print(start)
  12. def __setitem__(self, key, value):
  13. print(key,value)
  14. def __delitem__(self, key):
  15. print(key)
  16. f=Foo()
  17. f[1]
  18. f[5:3:5]
  19. 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__方法可以創建單例模式

類中的特殊成員