Java – does Python really create all binding methods for each new instance?
I'm reading the classes in python (3.4). According to my understanding, it seems that each new object has its own binding method instance
class A: def __init__(self,name): self.name = name def foo(self): print(self.name) a = A('One') b = A('Two') print(a.foo == b.foo)
The output is false
It seems to me a waste of memory I think the internal A.Foo and b.foo will point internally to a function in memory in some way: A.Foo will pass self as a class instance
I don't think this can be easily achieved in language
Does each new instance also contain a new instance of its binding method?
If so, is this detrimental to the performance of creating new objects, or is it more cautious than other languages that "share" methods between objects in Java?
Solution
Each time a method is accessed, it is bound on demand
Accessing the function name will call descriptor protocol, and the function object will return the binding method
The binding method is a thin wrapper around the function object; It stores references to original functions and instances When the method object is called, it passes the call to the function and inserts the instance as the first parameter
Methods are not created when creating instances, so a priori does not require additional memory
You can manually recreate the steps:
>>> class A: ... def __init__(self,name): ... self.name = name ... def foo(self): ... print(self.name) ... >>> a = A('One') >>> a.foo <bound method A.foo of <__main__.A object at 0x100a27978>> >>> a.foo.__self__ <__main__.A object at 0x100a27978> >>> a.foo.__func__ <function A.foo at 0x100a22598> >>> A.__dict__['foo'] <function A.foo at 0x100a22598> >>> A.__dict__['foo'].__get__(a,A) <bound method A.foo of <__main__.A object at 0x100a27978>> >>> A.__dict__['foo'].__get__(a,A)() One
Rebuild only method objects at a time; Basic functions remain stable:
>>> a.foo is a.foo False >>> b = A('Two') >>> b.foo is a.foo False >>> b.foo.__func__ is a.foo.__func__ True
This architecture also enables classmethod, staticmethod, and property objects to function You can create your own descriptors and create a series of interesting binding behaviors