根據wikipedia定義:
在電腦科學中,內省是指電腦程式在執行時(Runtime)檢查物件(Object)類型的一種能力,通常也可以稱作「執行時型別檢查"。一些程式語言如C++、Java、Ruby、PHP、Objective-C、Perl等等具有這種特性。
白話文就是:程式在運行時,有能力"動態"的查看變量的信息,這個能力就稱為內省。
以下我們來看個範例:
在Python中最常用的自省的方法是dir函式,它詳細的列出一個物件的特性。例如:
>>> dir(math.factorial)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
沒錯,函數使用__dir__儲存其擁有的屬性。
延伸:雖然不常見(但Django這麼做了),但我們也可以直接為函數賦予一個屬性:
>>> def upper_case_name(obj):
returm("%s %s" % (obj.first_name, obj.last_name)).upper()
>>> dir(upper_case_name)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> upper_case_name.short_description = 'Customer name' #直接為函數賦予一個屬性
>>> dir(upper_case_name) #發現新增了short_description屬性
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'short_description']
Reference:
https://jarvisma.gitbook.io/pythonlearn/2.3-han-shu-nei-sheng/chapter2.3 https://zh.wikipedia.org/wiki/%E5%86%85%E7%9C%81_(%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A7%91%E5%AD%A6) https://www.books.com.tw/products/0010706172
Share on Twitter Share on FacebookSQL Server Analytics Service 1
SEO(1) Github(2) Title Tag(2) ML(1) 李宏毅(1) SQL Server(18) Tempdb(1) SSMS(1) Windows(1) 自我成長(2) Excel(1) python Flask(1) python(5) Flask(2)
Max Chen (159)