Python Forum
Do objects get their own copy of the class methods? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Do objects get their own copy of the class methods? (/thread-15835.html)



Do objects get their own copy of the class methods? - Charles1 - Feb-02-2019

Hi,

Platform: Windows 10
Python version: 3.7

I came across a video on YouTube which suggested that objects

in Python get their own copies of the class methods.

If this is true then programs in Python must use a lot of memory.

The code below was an attempt to print the ids of the two methods.

The result was that both methods had the same id.

Would appreciate some clarification on this issue.

Thanks in advance for any help.

class Testing:
    def print_me(self):        
        print(id(self.print_me))
        
    def print_me2(self):        
        print(id(self.print_me2))
        
myTest = Testing()
myTest.print_me()
myTest.print_me2() 



RE: Do objects get their own copy of the class methods? - ichabod801 - Feb-02-2019

Your code doesn't test what you are asking about. You are asking about the same method of two different instances. You are testing two different methods of the same instance.

That said, I'm not sure what is going on with your results. The id of an object should be unique to that object and constant over it's lifespan. That two methods of the same instance have the same id means either they're the same object or their lifespans do not overlap.

I assigned the methods to other variables, and got different id's. That seems to imply that bound methods are created as needed. If you create one just for an id check, that id is freed up after the id check because the as-needed bound method goes away. That id is then reused for the second id check. However if you save the as-need bound method with a variable, a new id has to be picked for it.

I don't know for sure, that's just guessing based on the observed behavior.

Note that if you separately store the same method of the same instance in two different variables, they have different ids.