guxh的python筆記:特殊方法
阿新 • • 發佈:2019-01-13
class Foo: """this is Foo""" typecode = 'd' def __init__(self, x): self.x = x
__doc__:類的描述資訊
print(f.__doc__) # this is Foo
__module_:物件所屬modul,如果是當前執行檔案的即__main__,如果是import的,可以檢視所屬的module
print(f.__module__) # __main__
import pandas as pd df = pd.DataFrame() print(df.__module__) # pandas.core.frame
__class__:物件所屬類,等效於type
print(f.__class__) # <class '__main__.Foo'> print(type(f)) # <class '__main__.Foo'>
__call__:讓類的例項變為可呼叫
class Foo: def __call__(self, *args, **kwargs): return 1 print(Foo()()) # 1,第一次()是例項化,第二次()是呼叫
__dict__:
列印所有例項的屬性(不包括類屬性):
f = Foo(1) print(f.__dict__) # {'x': 1}
列印所有類屬性(不包括例項的屬性):
for k, v in Foo.__dict__.items(): print(k, v) 輸出為: __module__ : __main__
__doc__ : this is Foo
typecode : d
__init__ : <function Foo.__init__ at 0x000001AC45314620>
__dict__ : <attribute '__dict__' of 'Foo' objects>
__weakref__ : <attribute '__weakref__' of 'Foo' objects>
__getitem__、__setitem__、__delitem__:[]運算子,獲取/設定/刪除分量
__new__:待補充
__metaclass__:待補充
__init__:略
__del__:略
__str__:略
__repr__:略