Adding a Method to an Existing Object Instance

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

    What Jason Pratt posted is correct.

    >>> class Test(object):
    ...   def a(self):
    ...     pass
    ... 
    >>> def b(self):
    ...   pass
    ... 
    >>> Test.b = b
    >>> type(b)
    
    >>> type(Test.a)
    
    >>> type(Test.b)
    
    

    As you can see, Python doesn't consider b() any different than a(). In Python all methods are just variables that happen to be functions.

提交回复
热议问题