Adding a Method to an Existing Object Instance

后端 未结 16 3019
夕颜
夕颜 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条回答
  •  猫巷女王i
    2020-11-21 06:14

    What you're looking for is setattr I believe. Use this to set an attribute on an object.

    >>> def printme(s): print repr(s)
    >>> class A: pass
    >>> setattr(A,'printme',printme)
    >>> a = A()
    >>> a.printme() # s becomes the implicit 'self' variable
    < __ main __ . A instance at 0xABCDEFG>
    

提交回复
热议问题