Adding a Method to an Existing Object Instance

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

    You can use lambda to bind a method to an instance:

    def run(self):
        print self._instanceString
    
    class A(object):
        def __init__(self):
            self._instanceString = "This is instance string"
    
    a = A()
    a.run = lambda: run(a)
    a.run()
    

    Output:

    This is instance string
    

提交回复
热议问题