Adding a Method to an Existing Object Instance

后端 未结 16 3003
夕颜
夕颜 2020-11-21 05:45

I\'ve read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.

I understand that it\'s not always good to do so

16条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 06:11

    There are at least two ways for attach a method to an instance without types.MethodType:

    >>> class A:
    ...  def m(self):
    ...   print 'im m, invoked with: ', self
    
    >>> a = A()
    >>> a.m()
    im m, invoked with:  <__main__.A instance at 0x973ec6c>
    >>> a.m
    >
    >>> 
    >>> def foo(firstargument):
    ...  print 'im foo, invoked with: ', firstargument
    
    >>> foo
    
    

    1:

    >>> a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a))
    >>> a.foo()
    im foo, invoked with:  <__main__.A instance at 0x973ec6c>
    >>> a.foo
    >
    

    2:

    >>> instancemethod = type(A.m)
    >>> instancemethod
    
    >>> a.foo2 = instancemethod(foo, a, type(a))
    >>> a.foo2()
    im foo, invoked with:  <__main__.A instance at 0x973ec6c>
    >>> a.foo2
    >
    

    Useful links:
    Data model - invoking descriptors
    Descriptor HowTo Guide - invoking descriptors

提交回复
热议问题