Adding a Method to an Existing Object Instance

后端 未结 16 2961
夕颜
夕颜 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:00

    This question was opened years ago, but hey, there's an easy way to simulate the binding of a function to a class instance using decorators:

    def binder (function, instance):
      copy_of_function = type (function) (function.func_code, {})
      copy_of_function.__bind_to__ = instance
      def bound_function (*args, **kwargs):
        return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs)
      return bound_function
    
    
    class SupaClass (object):
      def __init__ (self):
        self.supaAttribute = 42
    
    
    def new_method (self):
      print self.supaAttribute
    
    
    supaInstance = SupaClass ()
    supaInstance.supMethod = binder (new_method, supaInstance)
    
    otherInstance = SupaClass ()
    otherInstance.supaAttribute = 72
    otherInstance.supMethod = binder (new_method, otherInstance)
    
    otherInstance.supMethod ()
    supaInstance.supMethod ()
    

    There, when you pass the function and the instance to the binder decorator, it will create a new function, with the same code object as the first one. Then, the given instance of the class is stored in an attribute of the newly created function. The decorator return a (third) function calling automatically the copied function, giving the instance as the first parameter.

    In conclusion you get a function simulating it's binding to the class instance. Letting the original function unchanged.

提交回复
热议问题