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

<p>I understand that it's not always good to do so. But how might one do this?</p>

[{'answer_id': 982, 'author': 'John Downey', 'author_id': 200, 'author_profile': 'https://Stackoverflow.com/users/200', 'pm_score': 5, 'selected': False, 'text': '<p>In Python monkeypatching generally works by overwriting a class or function\'s signature with your own. Below is an example from the <a href="http://web.archive.org/web/20130610034152/http://wiki.zope.org:80/zope2/MonkeyPatch" rel="noreferrer">Zope Wiki</a>:</p>\n<pre><code>from SomeOtherProduct.SomeModule import SomeClass\ndef speak(self):\n   return &quot;ook ook eee eee eee!&quot;\nSomeClass.speak = speak\n</code></pre>\n<p>This code will overwrite/create a method called <code>speak</code> in the class. In Jeff Atwood\'s <a href="https://blog.codinghorror.com/monkeypatching-for-humans/" rel="noreferrer">recent post on monkey patching</a>, he showed an example in C# 3.0 which is the current language I use for work.</p>\n'}, {'answer_id': 2982, 'author': 'Jason Pratt', 'author_id': 99, 'author_profile': 'https://Stackoverflow.com/users/99', 'pm_score': 11, 'selected': True, 'text': '<p>In Python, there is a difference between functions and bound methods.</p>\n<pre><code>&gt;&gt;&gt; def foo():\n...     print &quot;foo&quot;\n...\n&gt;&gt;&gt; class A:\n...     def bar( self ):\n...         print &quot;bar&quot;\n...\n&gt;&gt;&gt; a = A()\n&gt;&gt;&gt; foo\n&lt;function foo at 0x00A98D70&gt;\n&gt;&gt;&gt; a.bar\n&lt;bound method A.bar of &lt;__main__.A instance at 0x00A9BC88&gt;&gt;\n&gt;&gt;&gt;\n</code></pre>\n<p>Bound methods have been &quot;bound&quot; (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.</p>\n<p>Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:</p>\n<pre><code>&gt;&gt;&gt; def fooFighters( self ):\n...     print &quot;fooFighters&quot;\n...\n&gt;&gt;&gt; A.fooFighters = fooFighters\n&gt;&gt;&gt; a2 = A()\n&gt;&gt;&gt; a2.fooFighters\n&lt;bound method A.fooFighters of &lt;__main__.A instance at 0x00A9BEB8&gt;&gt;\n&gt;&gt;&gt; a2.fooFighters()\nfooFighters\n</code></pre>\n<p>Previously defined instances are updated as well (as long as they haven\'t overridden the attribute themselves):</p>\n<pre><code>&gt;&gt;&gt; a.fooFighters()\nfooFighters\n</code></pre>\n<p>The problem comes when you want to attach a method to a single instance:</p>\n<pre><code>&gt;&gt;&gt; def barFighters( self ):\n...     print &quot;barFighters&quot;\n...\n&gt;&gt;&gt; a.barFighters = barFighters\n&gt;&gt;&gt; a.barFighters()\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: barFighters() takes exactly 1 argument (0 given)\n</code></pre>\n<p>The function is not automatically bound when it\'s attached directly to an instance:</p>\n<pre><code>&gt;&gt;&gt; a.barFighters\n&lt;function barFighters at 0x00A98EF0&gt;\n</code></pre>\n<p>To bind it, we can use the <a href="https://docs.python.org/3/library/types.html#types.MethodType" rel="noreferrer">MethodType function in the types module</a>:</p>\n<pre><code>&gt;&gt;&gt; import types\n&gt;&gt;&gt; a.barFighters = types.MethodType( barFighters, a )\n&gt;&gt;&gt; a.barFighters\n&lt;bound method ?.barFighters of &lt;__main__.A instance at 0x00A9BC88&gt;&gt;\n&gt;&gt;&gt; a.barFighters()\nbarFighters\n</code></pre>\n<p>This time other instances of the class have not been affected:</p>\n<pre><code>&gt;&gt;&gt; a2.barFighters()\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nAttributeError: A instance has no attribute \'barFighters\'\n</code></pre>\n<p>More information can be found by reading about <a href="https://docs.python.org/3/howto/descriptor.html" rel="noreferrer">descriptors</a> and <a href="https://web.archive.org/web/20090124004817/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html" rel="noreferrer">metaclass</a> <a href="http://www.gnosis.cx/publish/programming/metaclass_2.html" rel="noreferrer">programming</a>.</p>\n'}, {'answer_id': 4600, 'author': 'HS.', 'author_id': 618, 'author_profile': 'https://Stackoverflow.com/users/618', 'pm_score': 4, 'selected': False, 'text': "<p>What you're looking for is <code>setattr</code> I believe.\nUse this to set an attribute on an object.</p>\n\n<pre><code>&gt;&gt;&gt; def printme(s): print repr(s)\n&gt;&gt;&gt; class A: pass\n&gt;&gt;&gt; setattr(A,'printme',printme)\n&gt;&gt;&gt; a = A()\n&gt;&gt;&gt; a.printme() # s becomes the implicit 'self' variable\n&lt; __ main __ . A instance at 0xABCDEFG&gt;\n</code></pre>\n"}, {'answer_id': 22525, 'author': 'Acuminate', 'author_id': 2482, 'author_profile': 'https://Stackoverflow.com/users/2482', 'pm_score': 2, 'selected': False, 'text': "<p>What Jason Pratt posted is correct.</p>\n\n<pre><code>&gt;&gt;&gt; class Test(object):\n...   def a(self):\n...     pass\n... \n&gt;&gt;&gt; def b(self):\n...   pass\n... \n&gt;&gt;&gt; Test.b = b\n&gt;&gt;&gt; type(b)\n&lt;type 'function'&gt;\n&gt;&gt;&gt; type(Test.a)\n&lt;type 'instancemethod'&gt;\n&gt;&gt;&gt; type(Test.b)\n&lt;type 'instancemethod'&gt;\n</code></pre>\n\n<p>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. </p>\n"}, {'answer_id': 959064, 'author': 'Evgeny', 'author_id': 110274, 'author_profile': 'https://Stackoverflow.com/users/110274', 'pm_score': 7, 'selected': False, 'text': '<p>Module <strong>new</strong> is deprecated since python 2.6 and removed in 3.0, use <strong>types</strong></p>\n\n<p>see <a href="http://docs.python.org/library/new.html" rel="noreferrer">http://docs.python.org/library/new.html</a></p>\n\n<p>In the example below I\'ve deliberately removed return value from <code>patch_me()</code> function.\nI think that giving return value may make one believe that patch returns a new object, which is not true - it modifies the incoming one. Probably this can facilitate a more disciplined use of monkeypatching.</p>\n\n<pre><code>import types\n\nclass A(object):#but seems to work for old style objects too\n    pass\n\ndef patch_me(target):\n    def method(target,x):\n        print "x=",x\n        print "called from", target\n    target.method = types.MethodType(method,target)\n    #add more if needed\n\na = A()\nprint a\n#out: &lt;__main__.A object at 0x2b73ac88bfd0&gt;  \npatch_me(a)    #patch instance\na.method(5)\n#out: x= 5\n#out: called from &lt;__main__.A object at 0x2b73ac88bfd0&gt;\npatch_me(A)\nA.method(6)        #can patch class too\n#out: x= 6\n#out: called from &lt;class \'__main__.A\'&gt;\n</code></pre>\n'}, {'answer_id': 8961717, 'author': 'Tomasz Zieliński', 'author_id': 176186, 'author_profile': 'https://Stackoverflow.com/users/176186', 'pm_score': 5, 'selected': False, 'text': '<p>I think that the above answers missed the key point. </p>\n\n<p>Let\'s have a class with a method:</p>\n\n<pre><code>class A(object):\n    def m(self):\n        pass\n</code></pre>\n\n<p>Now, let\'s play with it in ipython:</p>\n\n<pre><code>In [2]: A.m\nOut[2]: &lt;unbound method A.m&gt;\n</code></pre>\n\n<p>Ok, so <em>m()</em> somehow becomes an unbound method of <em>A</em>. But is it really like that?</p>\n\n<pre><code>In [5]: A.__dict__[\'m\']\nOut[5]: &lt;function m at 0xa66b8b4&gt;\n</code></pre>\n\n<p>It turns out that <em>m()</em> is just a function, reference to which is added to <em>A</em> class dictionary - there\'s no magic. Then why <em>A.m</em> gives us an unbound method? It\'s because the dot is not translated to a simple dictionary lookup. It\'s de facto a call of A.__class__.__getattribute__(A, \'m\'):</p>\n\n<pre><code>In [11]: class MetaA(type):\n   ....:     def __getattribute__(self, attr_name):\n   ....:         print str(self), \'-\', attr_name\n\nIn [12]: class A(object):\n   ....:     __metaclass__ = MetaA\n\nIn [23]: A.m\n&lt;class \'__main__.A\'&gt; - m\n&lt;class \'__main__.A\'&gt; - m\n</code></pre>\n\n<p>Now, I\'m not sure out of the top of my head why the last line is printed twice, but still it\'s clear what\'s going on there.</p>\n\n<p>Now, what the default __getattribute__ does is that it checks if the attribute is a so-called <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="noreferrer">descriptor</a> or not, i.e. if it implements a special __get__ method. If it implements that method, then what is returned is the result of calling that __get__ method. Going back to the first version of our <em>A</em> class, this is what we have:</p>\n\n<pre><code>In [28]: A.__dict__[\'m\'].__get__(None, A)\nOut[28]: &lt;unbound method A.m&gt;\n</code></pre>\n\n<p>And because Python functions implement the descriptor protocol, if they are called on behalf of an object, they bind themselves to that object in their __get__ method.</p>\n\n<p>Ok, so how to add a method to an existing object? Assuming you don\'t mind patching class, it\'s as simple as:</p>\n\n<pre><code>B.m = m\n</code></pre>\n\n<p>Then <em>B.m</em> "becomes" an unbound method, thanks to the descriptor magic.</p>\n\n<p>And if you want to add a method just to a single object, then you have to emulate the machinery yourself, by using types.MethodType:</p>\n\n<pre><code>b.m = types.MethodType(m, b)\n</code></pre>\n\n<p>By the way:</p>\n\n<pre><code>In [2]: A.m\nOut[2]: &lt;unbound method A.m&gt;\n\nIn [59]: type(A.m)\nOut[59]: &lt;type \'instancemethod\'&gt;\n\nIn [60]: type(b.m)\nOut[60]: &lt;type \'instancemethod\'&gt;\n\nIn [61]: types.MethodType\nOut[61]: &lt;type \'instancemethod\'&gt;\n</code></pre>\n'}, {'answer_id': 9041763, 'author': 'Nisan.H', 'author_id': 841337, 'author_profile': 'https://Stackoverflow.com/users/841337', 'pm_score': 3, 'selected': False, 'text': "<p>Consolidating Jason Pratt's and the community wiki answers, with a look at the results of different methods of binding:</p>\n\n<p>Especially note how adding the binding function as a class method <em>works</em>, but the referencing scope is incorrect.</p>\n\n<pre><code>#!/usr/bin/python -u\nimport types\nimport inspect\n\n## dynamically adding methods to a unique instance of a class\n\n\n# get a list of a class's method type attributes\ndef listattr(c):\n    for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]:\n        print m[0], m[1]\n\n# externally bind a function as a method of an instance of a class\ndef ADDMETHOD(c, method, name):\n    c.__dict__[name] = types.MethodType(method, c)\n\nclass C():\n    r = 10 # class attribute variable to test bound scope\n\n    def __init__(self):\n        pass\n\n    #internally bind a function as a method of self's class -- note that this one has issues!\n    def addmethod(self, method, name):\n        self.__dict__[name] = types.MethodType( method, self.__class__ )\n\n    # predfined function to compare with\n    def f0(self, x):\n        print 'f0\\tx = %d\\tr = %d' % ( x, self.r)\n\na = C() # created before modified instnace\nb = C() # modified instnace\n\n\ndef f1(self, x): # bind internally\n    print 'f1\\tx = %d\\tr = %d' % ( x, self.r )\ndef f2( self, x): # add to class instance's .__dict__ as method type\n    print 'f2\\tx = %d\\tr = %d' % ( x, self.r )\ndef f3( self, x): # assign to class as method type\n    print 'f3\\tx = %d\\tr = %d' % ( x, self.r )\ndef f4( self, x): # add to class instance's .__dict__ using a general function\n    print 'f4\\tx = %d\\tr = %d' % ( x, self.r )\n\n\nb.addmethod(f1, 'f1')\nb.__dict__['f2'] = types.MethodType( f2, b)\nb.f3 = types.MethodType( f3, b)\nADDMETHOD(b, f4, 'f4')\n\n\nb.f0(0) # OUT: f0   x = 0   r = 10\nb.f1(1) # OUT: f1   x = 1   r = 10\nb.f2(2) # OUT: f2   x = 2   r = 10\nb.f3(3) # OUT: f3   x = 3   r = 10\nb.f4(4) # OUT: f4   x = 4   r = 10\n\n\nk = 2\nprint 'changing b.r from {0} to {1}'.format(b.r, k)\nb.r = k\nprint 'new b.r = {0}'.format(b.r)\n\nb.f0(0) # OUT: f0   x = 0   r = 2\nb.f1(1) # OUT: f1   x = 1   r = 10  !!!!!!!!!\nb.f2(2) # OUT: f2   x = 2   r = 2\nb.f3(3) # OUT: f3   x = 3   r = 2\nb.f4(4) # OUT: f4   x = 4   r = 2\n\nc = C() # created after modifying instance\n\n# let's have a look at each instance's method type attributes\nprint '\\nattributes of a:'\nlistattr(a)\n# OUT:\n# attributes of a:\n# __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x000000000230FD88&gt;&gt;\n# addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x000000000230FD88&gt;&gt;\n# f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x000000000230FD88&gt;&gt;\n\nprint '\\nattributes of b:'\nlistattr(b)\n# OUT:\n# attributes of b:\n# __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt;\n# addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt;\n# f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt;\n# f1 &lt;bound method ?.f1 of &lt;class __main__.C at 0x000000000237AB28&gt;&gt;\n# f2 &lt;bound method ?.f2 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt;\n# f3 &lt;bound method ?.f3 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt;\n# f4 &lt;bound method ?.f4 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt;\n\nprint '\\nattributes of c:'\nlistattr(c)\n# OUT:\n# attributes of c:\n# __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x0000000002313108&gt;&gt;\n# addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x0000000002313108&gt;&gt;\n# f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x0000000002313108&gt;&gt;\n</code></pre>\n\n<p>Personally, I prefer the external ADDMETHOD function route, as it allows me to dynamically assign new method names within an iterator as well.</p>\n\n<pre><code>def y(self, x):\n    pass\nd = C()\nfor i in range(1,5):\n    ADDMETHOD(d, y, 'f%d' % i)\nprint '\\nattributes of d:'\nlistattr(d)\n# OUT:\n# attributes of d:\n# __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x0000000002303508&gt;&gt;\n# addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x0000000002303508&gt;&gt;\n# f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x0000000002303508&gt;&gt;\n# f1 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt;\n# f2 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt;\n# f3 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt;\n# f4 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt;\n</code></pre>\n"}, {'answer_id': 9636303, 'author': 'Tamzin Blake', 'author_id': 650551, 'author_profile': 'https://Stackoverflow.com/users/650551', 'pm_score': 3, 'selected': False, 'text': '<p>Since this question asked for non-Python versions, here\'s JavaScript:</p>\n\n<pre><code>a.methodname = function () { console.log("Yay, a new method!") }\n</code></pre>\n'}, {'answer_id': 16240409, 'author': 'ndpu', 'author_id': 1099876, 'author_profile': 'https://Stackoverflow.com/users/1099876', 'pm_score': 4, 'selected': False, 'text': '<p>There are at least two ways for attach a method to an instance without <code>types.MethodType</code>:</p>\n\n<pre><code>&gt;&gt;&gt; class A:\n...  def m(self):\n...   print \'im m, invoked with: \', self\n\n&gt;&gt;&gt; a = A()\n&gt;&gt;&gt; a.m()\nim m, invoked with:  &lt;__main__.A instance at 0x973ec6c&gt;\n&gt;&gt;&gt; a.m\n&lt;bound method A.m of &lt;__main__.A instance at 0x973ec6c&gt;&gt;\n&gt;&gt;&gt; \n&gt;&gt;&gt; def foo(firstargument):\n...  print \'im foo, invoked with: \', firstargument\n\n&gt;&gt;&gt; foo\n&lt;function foo at 0x978548c&gt;\n</code></pre>\n\n<p>1:</p>\n\n<pre><code>&gt;&gt;&gt; a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a))\n&gt;&gt;&gt; a.foo()\nim foo, invoked with:  &lt;__main__.A instance at 0x973ec6c&gt;\n&gt;&gt;&gt; a.foo\n&lt;bound method A.foo of &lt;__main__.A instance at 0x973ec6c&gt;&gt;\n</code></pre>\n\n<p>2:</p>\n\n<pre><code>&gt;&gt;&gt; instancemethod = type(A.m)\n&gt;&gt;&gt; instancemethod\n&lt;type \'instancemethod\'&gt;\n&gt;&gt;&gt; a.foo2 = instancemethod(foo, a, type(a))\n&gt;&gt;&gt; a.foo2()\nim foo, invoked with:  &lt;__main__.A instance at 0x973ec6c&gt;\n&gt;&gt;&gt; a.foo2\n&lt;bound method instance.foo of &lt;__main__.A instance at 0x973ec6c&gt;&gt;\n</code></pre>\n\n<p>Useful links:<br>\n<a href="http://docs.python.org/2/reference/datamodel.html#invoking-descriptors" rel="noreferrer">Data model - invoking descriptors</a><br>\n<a href="http://docs.python.org/2.7/howto/descriptor.html#invoking-descriptors" rel="noreferrer">Descriptor HowTo Guide - invoking descriptors</a></p>\n'}, {'answer_id': 24748849, 'author': 'ChristopherC', 'author_id': 1640404, 'author_profile': 'https://Stackoverflow.com/users/1640404', 'pm_score': 2, 'selected': False, 'text': '<p>If it can be of any help, I recently released a Python library named Gorilla to make the process of monkey patching more convenient.</p>\n\n<p>Using a function <code>needle()</code> to patch a module named <code>guineapig</code> goes as follows:</p>\n\n<pre><code>import gorilla\nimport guineapig\n@gorilla.patch(guineapig)\ndef needle():\n    print("awesome")\n</code></pre>\n\n<p>But it also takes care of more interesting use cases as shown in the <a href="http://gorilla.readthedocs.org/en/latest/faq.html" rel="nofollow">FAQ</a> from the <a href="http://gorilla.readthedocs.org/" rel="nofollow">documentation</a>.</p>\n\n<p>The code is available on <a href="https://github.com/christophercrouzet/gorilla" rel="nofollow">GitHub</a>.</p>\n'}, {'answer_id': 24865663, 'author': 'Evgeny Prokurat', 'author_id': 3748584, 'author_profile': 'https://Stackoverflow.com/users/3748584', 'pm_score': 4, 'selected': False, 'text': '<p>You can use lambda to bind a method to an instance:</p>\n\n<pre><code>def run(self):\n    print self._instanceString\n\nclass A(object):\n    def __init__(self):\n        self._instanceString = "This is instance string"\n\na = A()\na.run = lambda: run(a)\na.run()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>This is instance string\n</code></pre>\n'}, {'answer_id': 28060251, 'author': 'Russia Must Remove Putin', 'author_id': 541136, 'author_profile': 'https://Stackoverflow.com/users/541136', 'pm_score': 7, 'selected': False, 'text': '<p>Preface - a note on compatibility: other answers may only work in Python 2 - this answer should work perfectly well in Python 2 and 3. If writing Python 3 only, you might leave out explicitly inheriting from <code>object</code>, but otherwise the code should remain the same.</p>\n<blockquote>\n<h1>Adding a Method to an Existing Object Instance</h1>\n<p>I\'ve read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python.</p>\n<p>I understand that it\'s not always a good decision to do so. <strong>But, how might one do this?</strong></p>\n</blockquote>\n<h2>Yes, it is possible - But not recommended</h2>\n<p>I don\'t recommend this. This is a bad idea. Don\'t do it.</p>\n<p>Here\'s a couple of reasons:</p>\n<ul>\n<li>You\'ll add a bound object to every instance you do this to. If you do this a lot, you\'ll probably waste a lot of memory. Bound methods are typically only created for the short duration of their call, and they then cease to exist when automatically garbage collected. If you do this manually, you\'ll have a name binding referencing the bound method - which will prevent its garbage collection on usage.</li>\n<li>Object instances of a given type generally have its methods on all objects of that type. If you add methods elsewhere, some instances will have those methods and others will not. Programmers will not expect this, and you risk violating the <a href="https://en.wikipedia.org/wiki/Principle_of_least_astonishment" rel="noreferrer">rule of least surprise</a>.</li>\n<li>Since there are other really good reasons not to do this, you\'ll additionally give yourself a poor reputation if you do it.</li>\n</ul>\n<p>Thus, I suggest that you not do this unless you have a really good reason. <strong>It is far better to define the correct method in the class definition</strong> or <em>less</em> preferably to monkey-patch the class directly, like this:</p>\n<pre><code>Foo.sample_method = sample_method\n</code></pre>\n<p>Since it\'s instructive, however, I\'m going to show you some ways of doing this.</p>\n<h2>How it can be done</h2>\n<p>Here\'s some setup code. We need a class definition. It could be imported, but it really doesn\'t matter.</p>\n<pre><code>class Foo(object):\n    \'\'\'An empty class to demonstrate adding a method to an instance\'\'\'\n</code></pre>\n<p>Create an instance:</p>\n<pre><code>foo = Foo()\n</code></pre>\n<p>Create a method to add to it:</p>\n<pre><code>def sample_method(self, bar, baz):\n    print(bar + baz)\n</code></pre>\n<h3>Method nought (0) - use the descriptor method, <code>__get__</code></h3>\n<p>Dotted lookups on functions call the <code>__get__</code> method of the function with the instance, binding the object to the method and thus creating a &quot;bound method.&quot;</p>\n<pre><code>foo.sample_method = sample_method.__get__(foo)\n</code></pre>\n<p>and now:</p>\n<pre><code>&gt;&gt;&gt; foo.sample_method(1,2)\n3\n</code></pre>\n<h3>Method one - types.MethodType</h3>\n<p>First, import types, from which we\'ll get the method constructor:</p>\n<pre><code>import types\n</code></pre>\n<p>Now we add the method to the instance. To do this, we require the MethodType constructor from the <code>types</code> module (which we imported above).</p>\n<p>The argument signature for types.MethodType (in Python 3) is <code>(function, instance)</code>:</p>\n<pre><code>foo.sample_method = types.MethodType(sample_method, foo)\n</code></pre>\n<p>and usage:</p>\n<pre><code>&gt;&gt;&gt; foo.sample_method(1,2)\n3\n</code></pre>\n<p>Parenthetically, in Python 2 the signature was <code>(function, instance, class)</code>:</p>\n<pre><code>foo.sample_method = types.MethodType(sample_method, foo, Foo)\n</code></pre>\n<h3>Method two: lexical binding</h3>\n<p>First, we create a wrapper function that binds the method to the instance:</p>\n<pre><code>def bind(instance, method):\n    def binding_scope_fn(*args, **kwargs): \n        return method(instance, *args, **kwargs)\n    return binding_scope_fn\n</code></pre>\n<p>usage:</p>\n<pre><code>&gt;&gt;&gt; foo.sample_method = bind(foo, sample_method)    \n&gt;&gt;&gt; foo.sample_method(1,2)\n3\n</code></pre>\n<h3>Method three: functools.partial</h3>\n<p>A partial function applies the first argument(s) to a function (and optionally keyword arguments), and can later be called with the remaining arguments (and overriding keyword arguments). Thus:</p>\n<pre><code>&gt;&gt;&gt; from functools import partial\n&gt;&gt;&gt; foo.sample_method = partial(sample_method, foo)\n&gt;&gt;&gt; foo.sample_method(1,2)\n3    \n</code></pre>\n<p>This makes sense when you consider that bound methods are partial functions of the instance.</p>\n<h2>Unbound function as an object attribute - why this doesn\'t work:</h2>\n<p>If we try to add the sample_method in the same way as we might add it to the class, it is unbound from the instance, and doesn\'t take the implicit self as the first argument.</p>\n<pre><code>&gt;&gt;&gt; foo.sample_method = sample_method\n&gt;&gt;&gt; foo.sample_method(1,2)\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: sample_method() takes exactly 3 arguments (2 given)\n</code></pre>\n<p>We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn\'t actually use the <code>self</code> argument variable), but it would not be consistent with the expected signature of other instances (if we\'re monkey-patching this instance):</p>\n<pre><code>&gt;&gt;&gt; foo.sample_method(foo, 1, 2)\n3\n</code></pre>\n<h2>Conclusion</h2>\n<p>You now know several ways you <em>could</em> do this, but in all seriousness - don\'t do this.</p>\n'}, {'answer_id': 32076685, 'author': 'Max', 'author_id': 5010481, 'author_profile': 'https://Stackoverflow.com/users/5010481', 'pm_score': 3, 'selected': False, 'text': "<h1>This is actually an addon to the answer of &quot;Jason Pratt&quot;</h1>\n<p>Although Jasons answer works, it does only work if one wants to add a function to a class.\nIt did not work for me when I tried to reload an already existing method from the .py source code file.</p>\n<p>It took me for ages to find a workaround, but the trick seems simple...\n1.st import the code from the source code file\n2.nd force a reload\n3.rd use types.FunctionType(...) to convert the imported and bound method to a function\nyou can also pass on the current global variables, as the reloaded method would be in a different namespace\n4.th now you can continue as suggested by &quot;Jason Pratt&quot;\nusing the types.MethodType(...)</p>\n<p>Example:</p>\n<pre><code># this class resides inside ReloadCodeDemo.py\nclass A:\n    def bar( self ):\n        print &quot;bar1&quot;\n        \n    def reloadCode(self, methodName):\n        ''' use this function to reload any function of class A'''\n        import types\n        import ReloadCodeDemo as ReloadMod # import the code as module\n        reload (ReloadMod) # force a reload of the module\n        myM = getattr(ReloadMod.A,methodName) #get reloaded Method\n        myTempFunc = types.FunctionType(# convert the method to a simple function\n                                myM.im_func.func_code, #the methods code\n                                globals(), # globals to use\n                                argdefs=myM.im_func.func_defaults # default values for variables if any\n                                ) \n        myNewM = types.MethodType(myTempFunc,self,self.__class__) #convert the function to a method\n        setattr(self,methodName,myNewM) # add the method to the function\n\nif __name__ == '__main__':\n    a = A()\n    a.bar()\n    # now change your code and save the file\n    a.reloadCode('bar') # reloads the file\n    a.bar() # now executes the reloaded code\n</code></pre>\n"}, {'answer_id': 34404761, 'author': 'lain', 'author_id': 4548106, 'author_profile': 'https://Stackoverflow.com/users/4548106', 'pm_score': 3, 'selected': False, 'text': "<p>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:</p>\n\n<pre><code>def binder (function, instance):\n  copy_of_function = type (function) (function.func_code, {})\n  copy_of_function.__bind_to__ = instance\n  def bound_function (*args, **kwargs):\n    return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs)\n  return bound_function\n\n\nclass SupaClass (object):\n  def __init__ (self):\n    self.supaAttribute = 42\n\n\ndef new_method (self):\n  print self.supaAttribute\n\n\nsupaInstance = SupaClass ()\nsupaInstance.supMethod = binder (new_method, supaInstance)\n\notherInstance = SupaClass ()\notherInstance.supaAttribute = 72\notherInstance.supMethod = binder (new_method, otherInstance)\n\notherInstance.supMethod ()\nsupaInstance.supMethod ()\n</code></pre>\n\n<p>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.\n  <br/>\n  <br/>\nIn conclusion you get a function simulating it's binding to the class instance. Letting the original function unchanged.</p>\n"}, {'answer_id': 43703054, 'author': 'Yu Feng', 'author_id': 3781929, 'author_profile': 'https://Stackoverflow.com/users/3781929', 'pm_score': 3, 'selected': False, 'text': '<p>I find it strange that nobody mentioned that all of the methods listed above creates a cycle reference between the added method and the instance, causing the object to be persistent till garbage collection. There was an old trick adding a descriptor by extending the class of the object:</p>\n\n<pre><code>def addmethod(obj, name, func):\n    klass = obj.__class__\n    subclass = type(klass.__name__, (klass,), {})\n    setattr(subclass, name, func)\n    obj.__class__ = subclass\n</code></pre>\n'}, {'answer_id': 45341362, 'author': 'Arturo Morales Rangel', 'author_id': 4475534, 'author_profile': 'https://Stackoverflow.com/users/4475534', 'pm_score': 2, 'selected': False, 'text': "<pre><code>from types import MethodType\n\ndef method(self):\n   print 'hi!'\n\n\nsetattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )\n</code></pre>\n\n<p>With this, you can use the self pointer</p>\n"}, {'answer_id': 64950870, 'author': 'danbst', 'author_id': 1190453, 'author_profile': 'https://Stackoverflow.com/users/1190453', 'pm_score': -1, 'selected': False, 'text': "<p>Apart from what others said, I found that <code>__repr__</code> and <code>__str__</code> methods can't be monkeypatched on object level, because <code>repr()</code> and <code>str()</code> use class-methods, not locally-bounded object methods:</p>\n<pre><code># Instance monkeypatch\n[ins] In [55]: x.__str__ = show.__get__(x)                                                                 \n\n[ins] In [56]: x                                                                                           \nOut[56]: &lt;__main__.X at 0x7fc207180c10&gt;\n\n[ins] In [57]: str(x)                                                                                      \nOut[57]: '&lt;__main__.X object at 0x7fc207180c10&gt;'\n\n[ins] In [58]: x.__str__()                                                                                 \nNice object!\n\n# Class monkeypatch\n[ins] In [62]: X.__str__ = lambda _: &quot;From class&quot;                                                          \n\n[ins] In [63]: str(x)                                                                                      \nOut[63]: 'From class'\n</code></pre>\n"}, {'answer_id': 70662971, 'author': 'Gerard G', 'author_id': 7452220, 'author_profile': 'https://Stackoverflow.com/users/7452220', 'pm_score': 0, 'selected': False, 'text': "<h1>How to recover a class from an instance of a class</h1>\n<pre><code>class UnderWater:\n    def __init__(self):\n        self.net = 'underwater'\n\nmarine = UnderWater() # Instantiate the class\n\n# Recover the class from the instance and add attributes to it.\nclass SubMarine(marine.__class__):  \n    def __init__(self):\n        super().__init__()\n            self.sound = 'Sonar'\n    \nprint(SubMarine, SubMarine.__name__, SubMarine().net, SubMarine().sound)\n\n# Output\n# (__main__.SubMarine,'SubMarine', 'underwater', 'Sonar')\n</code></pre>\n"}, {'answer_id': 73486831, 'author': 'Hans', 'author_id': 15096247, 'author_profile': 'https://Stackoverflow.com/users/15096247', 'pm_score': 1, 'selected': False, 'text': '<p>Thanks to Arturo!\nYour answer got me on the right track!</p>\n<p>Based on Arturo\'s code, I wrote a little class:</p>\n<pre><code>from types import MethodType\nimport re\nfrom string import ascii_letters\n\n\nclass DynamicAttr:\n    def __init__(self):\n        self.dict_all_files = {}\n\n    def _copy_files(self, *args, **kwargs):\n        print(f\'copy {args[0][&quot;filename&quot;]} {args[0][&quot;copy_command&quot;]}\')\n\n    def _delete_files(self, *args, **kwargs):\n        print(f\'delete {args[0][&quot;filename&quot;]} {args[0][&quot;delete_command&quot;]}\')\n\n    def _create_properties(self):\n        for key, item in self.dict_all_files.items():\n            setattr(\n                self,\n                key,\n                self.dict_all_files[key],\n            )\n            setattr(\n                self,\n                key + &quot;_delete&quot;,\n                MethodType(\n                    self._delete_files,\n                    {\n                        &quot;filename&quot;: key,\n                        &quot;delete_command&quot;: f\'del {item}\',\n                    },\n                ),\n            )\n            setattr(\n                self,\n                key + &quot;_copy&quot;,\n                MethodType(\n                    self._copy_files,\n                    {\n                        &quot;filename&quot;: key,\n                        &quot;copy_command&quot;: f\'copy {item}\',\n                    },\n                ),\n            )\n    def add_files_to_class(self, filelist: list):\n        for _ in filelist:\n            attr_key = re.sub(rf\'[^{ascii_letters}]+\', \'_\', _).strip(\'_\')\n            self.dict_all_files[attr_key] = _\n        self._create_properties()\ndy = DynamicAttr()\ndy.add_files_to_class([r&quot;C:\\Windows\\notepad.exe&quot;, r&quot;C:\\Windows\\regedit.exe&quot;])\n\ndy.add_files_to_class([r&quot;C:\\Windows\\HelpPane.exe&quot;, r&quot;C:\\Windows\\win.ini&quot;])\n#output\nprint(dy.C_Windows_HelpPane_exe)\ndy.C_Windows_notepad_exe_delete()\ndy.C_Windows_HelpPane_exe_copy()\nC:\\Windows\\HelpPane.exe\ndelete C_Windows_notepad_exe del C:\\Windows\\notepad.exe\ncopy C_Windows_HelpPane_exe copy C:\\Windows\\HelpPane.exe\n</code></pre>\n<p><img src="https://i.imgur.com/d2eX4Lj.png" alt="result" /></p>\n<p>This class allows you to add new attributes and methods at any time.</p>\n<p><strong>Edit:</strong></p>\n<p>Here is a more generalized solution:</p>\n<pre><code>import inspect\nimport re\nfrom copy import deepcopy\nfrom string import ascii_letters\n\n\ndef copy_func(f):\n    if callable(f):\n        if inspect.ismethod(f) or inspect.isfunction(f):\n            g = lambda *args, **kwargs: f(*args, **kwargs)\n            t = list(filter(lambda prop: not (&quot;__&quot; in prop), dir(f)))\n            i = 0\n            while i &lt; len(t):\n                setattr(g, t[i], getattr(f, t[i]))\n                i += 1\n            return g\n    dcoi = deepcopy([f])\n    return dcoi[0]\n\n\nclass FlexiblePartial:\n    def __init__(self, func, this_args_first, *args, **kwargs):\n\n        try:\n            self.f = copy_func(func)  # create a copy of the function\n        except Exception:\n            self.f = func\n        self.this_args_first = this_args_first  # where should the other (optional) arguments be that are passed when the function is called\n        try:\n            self.modulename = args[0].__class__.__name__  # to make repr look good\n        except Exception:\n            self.modulename = &quot;self&quot;\n\n        try:\n            self.functionname = func.__name__  # to make repr look good\n        except Exception:\n            try:\n                self.functionname = func.__qualname__  # to make repr look good\n            except Exception:\n                self.functionname = &quot;func&quot;\n\n        self.args = args\n        self.kwargs = kwargs\n\n        self.name_to_print = self._create_name()  # to make repr look good\n\n    def _create_name(self):\n        stra = self.modulename + &quot;.&quot; + self.functionname + &quot;(self, &quot;\n        for _ in self.args[1:]:\n            stra = stra + repr(_) + &quot;, &quot;\n        for key, item in self.kwargs.items():\n            stra = stra + str(key) + &quot;=&quot; + repr(item) + &quot;, &quot;\n        stra = stra.rstrip().rstrip(&quot;,&quot;)\n        stra += &quot;)&quot;\n        if len(stra) &gt; 100:\n            stra = stra[:95] + &quot;...)&quot;\n        return stra\n\n    def __call__(self, *args, **kwargs):\n        newdic = {}\n        newdic.update(self.kwargs)\n        newdic.update(kwargs)\n        if self.this_args_first:\n            return self.f(*self.args[1:], *args, **newdic)\n\n        else:\n\n            return self.f(*args, *self.args[1:], **newdic)\n\n    def __str__(self):\n        return self.name_to_print\n\n    def __repr__(self):\n        return self.__str__()\n\n\nclass AddMethodsAndProperties:\n    def add_methods(self, dict_to_add):\n        for key_, item in dict_to_add.items():\n            key = re.sub(rf&quot;[^{ascii_letters}]+&quot;, &quot;_&quot;, str(key_)).rstrip(&quot;_&quot;)\n            if isinstance(item, dict):\n                if &quot;function&quot; in item:  # for adding methods\n                    if not isinstance(\n                        item[&quot;function&quot;], str\n                    ):  # for external functions that are not part of the class\n                        setattr(\n                            self,\n                            key,\n                            FlexiblePartial(\n                                item[&quot;function&quot;],\n                                item[&quot;this_args_first&quot;],\n                                self,\n                                *item[&quot;args&quot;],\n                                **item[&quot;kwargs&quot;],\n                            ),\n                        )\n\n                    else:\n                        setattr(\n                            self,\n                            key,\n                            FlexiblePartial(\n                                getattr(\n                                    self, item[&quot;function&quot;]\n                                ),  # for internal functions - part of the class\n                                item[&quot;this_args_first&quot;],\n                                self,\n                                *item[&quot;args&quot;],\n                                **item[&quot;kwargs&quot;],\n                            ),\n                        )\n            else:  # for adding props\n                setattr(self, key, item)\n</code></pre>\n<p>Let\'s test it:</p>\n<pre><code>class NewClass(AddMethodsAndProperties): #inherit from AddMethodsAndProperties to add the method add_methods\n    def __init__(self):\n        self.bubu = 5\n\n    def _delete_files(self, file): #some random methods \n        print(f&quot;File will be deleted: {file}&quot;)\n\n    def delete_files(self, file):\n        self._delete_files(file)\n\n    def _copy_files(self, file, dst):\n        print(f&quot;File will be copied: {file} Dest: {dst}&quot;)\n\n    def copy_files(self, file, dst):\n        self._copy_files(file, dst)\n\n    def _create_files(self, file, folder):\n        print(f&quot;File will be created: {file} {folder}&quot;)\n\n    def create_files(self, file, folder):\n        self._create_files(file, folder)\n\n    def method_with_more_kwargs(self, file, folder, one_more):\n        print(file, folder, one_more)\n        return self\n\n\nnc = NewClass()\ndict_all_files = {\n    r&quot;C:\\Windows\\notepad.exe_delete&quot;: {\n        &quot;function&quot;: &quot;delete_files&quot;,\n        &quot;args&quot;: (),\n        &quot;kwargs&quot;: {&quot;file&quot;: r&quot;C:\\Windows\\notepad.exe&quot;},\n        &quot;this_args_first&quot;: True,\n    },\n    r&quot;C:\\Windows\\notepad.exe_argsfirst&quot;: {\n        &quot;function&quot;: &quot;delete_files&quot;,\n        &quot;args&quot;: (),\n        &quot;kwargs&quot;: {&quot;file&quot;: r&quot;C:\\Windows\\notepad.exe&quot;},\n        &quot;this_args_first&quot;: True,\n    },\n    r&quot;C:\\Windows\\notepad.exe_copy&quot;: {\n        &quot;function&quot;: &quot;copy_files&quot;,\n        &quot;args&quot;: (),\n        &quot;kwargs&quot;: {\n            &quot;file&quot;: r&quot;C:\\Windows\\notepad.exe&quot;,\n            &quot;dst&quot;: r&quot;C:\\Windows\\notepad555.exe&quot;,\n        },\n        &quot;this_args_first&quot;: True,\n    },\n    r&quot;C:\\Windows\\notepad.exe_create&quot;: {\n        &quot;function&quot;: &quot;create_files&quot;,\n        &quot;args&quot;: (),\n        &quot;kwargs&quot;: {&quot;file&quot;: r&quot;C:\\Windows\\notepad.exe&quot;, &quot;folder&quot;: &quot;c:\\\\windows95&quot;},\n        &quot;this_args_first&quot;: True,\n    },\n    r&quot;C:\\Windows\\notepad.exe_upper&quot;: {\n        &quot;function&quot;: str.upper,\n        &quot;args&quot;: (r&quot;C:\\Windows\\notepad.exe&quot;,),\n        &quot;kwargs&quot;: {},\n        &quot;this_args_first&quot;: True,\n    },\n    r&quot;C:\\Windows\\notepad.exe_method_with_more_kwargs&quot;: {\n        &quot;function&quot;: &quot;method_with_more_kwargs&quot;,\n        &quot;args&quot;: (),\n        &quot;kwargs&quot;: {&quot;file&quot;: r&quot;C:\\Windows\\notepad.exe&quot;, &quot;folder&quot;: &quot;c:\\\\windows95&quot;},\n        &quot;this_args_first&quot;: True,\n    },\n    r&quot;C:\\Windows\\notepad.exe_method_with_more_kwargs_as_args_first&quot;: {\n        &quot;function&quot;: &quot;method_with_more_kwargs&quot;,\n        &quot;args&quot;: (r&quot;C:\\Windows\\notepad.exe&quot;, &quot;c:\\\\windows95&quot;),\n        &quot;kwargs&quot;: {},\n        &quot;this_args_first&quot;: True,\n    },\n    r&quot;C:\\Windows\\notepad.exe_method_with_more_kwargs_as_args_last&quot;: {\n        &quot;function&quot;: &quot;method_with_more_kwargs&quot;,\n        &quot;args&quot;: (r&quot;C:\\Windows\\notepad.exe&quot;, &quot;c:\\\\windows95&quot;),\n        &quot;kwargs&quot;: {},\n        &quot;this_args_first&quot;: False,\n    },\n    &quot;this_is_a_list&quot;: [55, 3, 3, 1, 4, 43],\n}\n\nnc.add_methods(dict_all_files)\n\n\nprint(nc.C_Windows_notepad_exe_delete)\nprint(nc.C_Windows_notepad_exe_delete(), end=&quot;\\n\\n&quot;)\nprint(nc.C_Windows_notepad_exe_argsfirst)\nprint(nc.C_Windows_notepad_exe_argsfirst(), end=&quot;\\n\\n&quot;)\nprint(nc.C_Windows_notepad_exe_copy)\nprint(nc.C_Windows_notepad_exe_copy(), end=&quot;\\n\\n&quot;)\nprint(nc.C_Windows_notepad_exe_create)\nprint(nc.C_Windows_notepad_exe_create(), end=&quot;\\n\\n&quot;)\nprint(nc.C_Windows_notepad_exe_upper)\nprint(nc.C_Windows_notepad_exe_upper(), end=&quot;\\n\\n&quot;)\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs)\nprint(\n    nc.C_Windows_notepad_exe_method_with_more_kwargs(\n        one_more=&quot;f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs(\n        one_more=&quot;f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs(\n        one_more=&quot;f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;\n    ),\n    end=&quot;\\n\\n&quot;,\n)\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first)\nprint(\n    nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n        &quot;f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa&quot;\n    ),\n    end=&quot;\\n\\n&quot;,\n)\nprint(\n    nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n        &quot;f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n        &quot;f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n        &quot;f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;\n    ),\n    end=&quot;\\n\\n&quot;,\n)\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last)\nprint(\n    nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;\n    ),\n    end=&quot;\\n\\n&quot;,\n)\nprint(\n    nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;\n    ),\n    end=&quot;\\n\\n&quot;,\n)\nprint(nc.this_is_a_list)\ncheckit = (\n    nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ&quot;\n    )\n    .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n        &quot;f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;\n    )\n)\nprint(f\'nc is checkit? -&gt; {nc is checkit}\')\n\n\n#output:\n\n\nNewClass.delete_files(self, file=\'C:\\\\Windows\\\\notepad.exe\')\nFile will be deleted: C:\\Windows\\notepad.exe\nNone\n\n\nNewClass.delete_files(self, file=\'C:\\\\Windows\\\\notepad.exe\')\nFile will be deleted: C:\\Windows\\notepad.exe\nNone\n\n\nNewClass.copy_files(self, file=\'C:\\\\Windows\\\\notepad.exe\', dst=\'C:\\\\Windows\\\\notepad555.exe\')\nFile will be copied: C:\\Windows\\notepad.exe Dest: C:\\Windows\\notepad555.exe\nNone\n\n\nNewClass.create_files(self, file=\'C:\\\\Windows\\\\notepad.exe\', folder=\'c:\\\\windows95\')\nFile will be created: C:\\Windows\\notepad.exe c:\\windows95\nNone\n\n\nNewClass.upper(self, \'C:\\\\Windows\\\\notepad.exe\')\nC:\\WINDOWS\\NOTEPAD.EXE\n\n\nNewClass.method_with_more_kwargs(self, file=\'C:\\\\Windows\\\\notepad.exe\', folder=\'c:\\\\windows95\')\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\nC:\\Windows\\notepad.exe c:\\windows95 f:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\nC:\\Windows\\notepad.exe c:\\windows95 f:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n&lt;__main__.NewClass object at 0x0000000005F199A0&gt;\n\n\nNewClass.method_with_more_kwargs(self, \'C:\\\\Windows\\\\notepad.exe\', \'c:\\\\windows95\')\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\n&lt;__main__.NewClass object at 0x0000000005F199A0&gt;\n\n\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\nC:\\Windows\\notepad.exe c:\\windows95 f:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\nC:\\Windows\\notepad.exe c:\\windows95 f:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n&lt;__main__.NewClass object at 0x0000000005F199A0&gt;\n\n\nNewClass.method_with_more_kwargs(self, \'C:\\\\Windows\\\\notepad.exe\', \'c:\\\\windows95\')\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n&lt;__main__.NewClass object at 0x0000000005F199A0&gt;\n\n\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n&lt;__main__.NewClass object at 0x0000000005F199A0&gt;\n\n\n[55, 3, 3, 1, 4, 43]\n\n\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n\n\nnc is checkit? -&gt; True\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/145/']