zoukankan      html  css  js  c++  java
  • 零基础学python-18.5 函数的内建工具与函数的属性

    这一章节我们来讨论python函数的另外两个方面:函数的内建工具与函数的属性

    1.函数的内建工具

    函数作为是对象,他也可以使用内建函数来管理,例如:

    >>> def test():
    	pass
    
    >>> test.__name__
    'test'
    >>> dir(test)
    ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
    >>> test.__code__
    <code object test at 0x0133B7A0, file "<pyshell#2>", line 1>
    >>> test.__class__
    <class 'function'>
    >>> 


    我们上面的代码只是建立了一个空函数,然后我们使用dir()这个内建函数检测test的时候,其实test还包括很多其他的属性

    我们可以利用这些属性来管理函数,特别是后面我们将会讲到的装饰器

    2.函数的属性

    由于函数就是对像,所以我们可以为它附加属性,作为函数的静态属性

    >>> def test():
    	pass
    
    >>> test.count=0
    >>> test.count
    0
    >>> test.count +=2
    >>> test.count
    2
    >>> test()


    从上面的代码可以看见,我们为test附加了count的属性,然后对count进行运算等操作

    但是有一点需要注意的是:如果test在建立的时候就想着对count操作,但是又不建立count,而是在后来附加,这个时候就会报错

    >>> def test():
    	print(count)
    
    	
    >>> test.count=0
    >>> test()
    Traceback (most recent call last):
      File "<pyshell#18>", line 1, in <module>
        test()
      File "<pyshell#16>", line 2, in test
        print(count)
    NameError: name 'count' is not defined
    >>> 


    总结:这一章节简单介绍了函数的内建工具与函数的属性

    这一章节就说到这里,谢谢大家

    ------------------------------------------------------------------

    点击跳转零基础学python-目录

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    运维:生产日志重复打印了,赶紧来看看~
    就这样,我走过了程序员的前五年。一路风雨泥泞,前方阳光正好。
    一个排序引发的BUG
    曝光一个网站,我周末就耗在上面了。
    我不服!这开源项目居然才888个星!?
    知乎的一次29.7元的咨询
    面试官:啥是请求重放呀?
    414天前,我以为这是编程玄学...
    老爷子这代码,看跪了!
    面试官一个线程池问题把我问懵逼了。
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4896726.html
Copyright © 2011-2022 走看看