Python-向现有对象实例添加方法

发布于 2021-02-02 23:23:50

我已经读到,可以在Python中添加一个方法到现有对象(即,不是在类定义中)。 我知道这样做并不总是好的。但我们怎么做呢?

关注者
0
被浏览
215
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    在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'
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看