Python的locals()函数
生活随笔
收集整理的這篇文章主要介紹了
Python的locals()函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python的locals()函數會以dict類型返回當前位置的全部局部變量。
示例代碼:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def func():arg_a, arg_b = 'a', 'b'def func_a():passdef func_b():passdef print_value():print(arg_a, arg_b)return locals()if __name__ == '__main__':args = func()print(type(args))print(args)運行結果可以看出,會將函數func的局部變量以dict類型返回。
<class 'dict'> {'func_a': <function func.<locals>.func_a at 0x10d8f71e0>, 'arg_b': 'b', 'arg_a': 'a', 'print_value': <function func.<locals>.print_value at 0x10d8f7378>, 'func_b': <function func.<locals>.func_b at 0x10d8f72f0>}將locals()與property結合提高代碼可讀性
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' class NewProps(object):def __init__(self):self._age = 40def fage():doc = "The age property."def fset(self, value):self._age = int(value)def fget(self):return self._agedef fdel(self):del self._agereturn locals()age = property(**fage())if __name__ == '__main__':x = NewProps()print(x.age)x.age = 50print(x.age)這里需要注意的是fage()方法下4個屬性名稱不能修改(也不能新增其他屬性,除非對locals()返回的dict進行處理,移除多余的元素),必須為fset、fget、fdel、doc,如果修改屬性名稱,會拋出如下異常:
'f_set' is an invalid keyword argument for this function因為,property的__init__方法接收4個參數(self除外,因為Python編譯器會自動把self傳入)
def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__.....在return locals()時,返回dict,key的值和參數的name一一對應,以**kwargs參數的形式傳入property的__init__方法。
當然,更好的方法是使用property裝飾器。
總結
以上是生活随笔為你收集整理的Python的locals()函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: inspect模块---检查活动对象
- 下一篇: Python内置函数查询表——总结篇