In our codebase there is Python and C++ married by SWIG. The C++ classes are sometimes given Python extensions like so:
%pythoncode %{
def DiscreteKey_baseData(self, baseData):
pass
def DiscreteKey_asSet(self):
pass
DiscreteKey.baseData = new_instancemethod(DiscreteKey_baseData, None, DiscreteKey)
DiscreteKey.asSet = new_instancemethod(DiscreteKey_asSet, None, DiscreteKey)
%}
or
%pythoncode %{
def ParmID_hash(parmID):
return hash(str(parmID))
ParmID.__hash__ = ParmID_hash
%}
What is the difference between using new.instancemethod to attach a method to a class, vs. simply assigning it, as in the second example? Could the first example be changed to simply
DiscreteKey.baseData = DiscreteKey_baseData
DiscreteKey.asSet = DiscreteKey_asSet
? (note that baseData takes another argument)
Or is the second example actually deficient in some way, and should be using new_instancemethod too?
Assigning a function to a class attribute, and doing the same via
new_instancemethod()(which I assume is a Swig alias for the method constructor, e.g.types.MethodType) are exactly equivalent. You can tell by checkingtype(DiscreteKey.baseData). Regardless of how the method was assigned, it will be<type 'instancemethod'>.The
new_instancemethod()constructor is useful when assigning functions onto instances, however. This won’t work without the method “wrapper.”