Safely bind method from one class to another class in Python [duplicate]

2024/9/20 0:18:09

I know I can attach a function to a class and make it a method:

 >>> def is_not_bound(inst, name):
...     print("Hello %s" % name)
... 
>>> 
>>> class NoMethods:
...     pass
... 
>>> 
>>> setattr(NoMethods, 'bound', is_not_bound)
>>> 
>>> NoMethods().bound("oz") # prints: Hello oz
Hello oz

To my surprise this works also with a bound method from one class to another:

>>> class Foo:
...     def foo(self, name):
...         print("Hello %s" % name)
... 
>>> class B:
...     pass
... 
>>> setattr(B, 'bound_to_b', getattr(Foo, 'foo'))
>>> B().bound_to_b("confused?")
Hello confused?
>>> 

Can I safely use this? Is there something I am overseeing?

update

One caveat that I found already:

>>> B.bound_to_b
<function Foo.foo at 0x7fc997e8b730>

Even though I called the method from B, It seems bound to Foo.

And even more surprising!:

>>> def new_method(self, addto):
...     return self.num + addto
... 
>>> setattr(B, 'add', new_method)
>>> b=B()
>>> b.num = 2
>>> b.add(2)
4
Answer

Apparently, this is an intended behavior (which is cool!). But also apparently, this behavior is not very familiar.

If you knew Python 2 for a long time, you would might not be aware of the fact that Python 3 has no methods (as commented above).

So in Python 3:

>>> class Foo:
...     def foo(self, name):
...         print("Hello %s" % name)
... 
>>> Foo.foo
<function Foo.foo at 0x7f729a406730>
>>> def foo():
...     pass
... 
>>> foo
<function foo at 0x7f729b83ff28>
>>> 
>>> Foo.foo
<function Foo.foo at 0x7f729a406730>

There is no distinction! In Python 2 however:

Python 2.7.14 (default, Feb  2 2018, 02:17:12) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def foo(self, name):
...         print("Hello %s" % name)
... 
>>> Foo.foo
<unbound method Foo.foo>
>>> 
https://en.xdnf.cn/q/72220.html

Related Q&A

Basic Python OpenCV cropping and resizing

can someone help me with a little cropping algorithm? its openCV.. im trying to figure this out. I know the method is crop = image[y:y1, x:x1]. If I have an image with new_dimensionXxnew_dimensionY pi…

Why does Keras loss drop dramatically after the first epoch?

Im training a U-Net CNN in Keras/Tensorflow and find that loss massively decreases between the last batch of the first epoch, and the first batch of the second epoch: Epoch 00001: loss improved from in…

extract strings from a binary file in python

I have a project where I am given a file and i need to extract the strings from the file. Basically think of the "strings" command in linux but im doing this in python. The next condition is …

Installing numpy on Mac to work on AWS Lambda

Is there a way to install numpy on a Mac so that it will work when uploaded to AWS Lambda? I have tried a variety of different ways, including using different pip versions, using easy_install, and fol…

python- how to get the output of the function used in Timer

I want to run a function for 10s then do other stuff. This is my code using Timerfrom threading import Timer import timedef timeout():b=truereturn ba=false t = Timer(10,timeout) t.start()while(a==f…

Create automated tests for interactive shell based on Pythons cmd module

I am building an interactive shell using Python 3 and the cmd module. I have already written simple unit tests using py.test to test the individual functions, such as the do_* functions. Id like to c…

Matplotlib with multiprocessing freeze computer

I have an issue with matplotlib and multiprocessing. I launch a first process, where I display an image and select an area, and close the figure. Then I launch another process, where I call a graph fun…

Pull Tag Value using BeautifulSoup

Can someone direct me as how to pull the value of a tag using BeautifulSoup? I read the documentation but had a hard time navigating through it. For example, if I had:<span title="Funstuff&qu…

What is the practical difference between xml, json, rss and atom when interfacing with Twitter?

Im new to web services and as an introduction Im playing around with the Twitter API using the Twisted framework in python. Ive read up on the different formats they offer, but its still not clear to m…

how to grab from JSON in selenium python

My page returns JSON http response which contains id: 14Is there a way in selenium python to grab this? I searched the web and could not find any solutions. Now I am wondering maybe its just not poss…