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-目录

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

  • 相关阅读:
    sql 用Group by分组后,取每组的前几条记录
    mac安装 配置 ant
    js日期时间比较函数
    hibernate下载包中配置文件路径
    dbvis MySQL server version for the right syntax to use near 'OPTION SQL_SELECT_LIMIT=DEFAULT' at line 1
    严重: Exception starting filter struts2解决方法!
    【Linux】进程优先级、进程nice值和%nice
    【Algorithm】二分查找
    【php】thinkphp以post方式查询时分页失效的解决方法
    【C语言】练习5-8
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4896726.html
Copyright © 2011-2022 走看看