栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python

在Python中,函数和绑定方法之间存在差异。

>>> def foo():...     print "foo"...>>> class A:...     def bar( self ):...         print "bar"...>>> a = A()>>> foo<function foo at 0x00A98D70>>>> a.bar<bound method A.bar of <__main__.A instance at 0x00A9BC88>>>>>

绑定方法已“绑定”(描述性)到一个实例,并且无论何时调用该方法,该实例都将作为第一个参数传递。

但是,作为类(而不是实例)的属性的可调用对象仍未绑定,因此你可以在需要时随时修改类定义:

>>> def fooFighters( self ):...     print "fooFighters"...>>> A.fooFighters = fooFighters>>> a2 = A()>>> a2.fooFighters<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>>>> a2.fooFighters()fooFighters

先前定义的实例也会被更新(只要它们本身没有覆盖属性):

>>> a.fooFighters()fooFighters

当你要将方法附加到单个实例时,就会出现问题:

>>> def barFighters( self ):...     print "barFighters"...>>> a.barFighters = barFighters>>> a.barFighters()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: barFighters() takes exactly 1 argument (0 given)

该函数直接附加到实例时不会自动绑定:

>>> a.barFighters<function barFighters at 0x00A98EF0>

要绑定它,我们可以在类型模块中使用MethodType函数:

>>> import types>>> a.barFighters = types.MethodType( barFighters, a )>>> a.barFighters<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>>>> a.barFighters()barFighters

这次,该类的其他实例没有受到影响:

>>> a2.barFighters()Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: A instance has no attribute 'barFighters'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/372205.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号