python - How can i change the __cmp__ function of an instance (not in class)? -
How can I change the __cmp__ function of an example (not in the class)?
Ex:
class foo: def __init __ (self, num): self.num = num def cmp (self, others): return self.num - other Class work foo in the .num # class __cmp__ function as the example __cmp__ = cmp a = foo (1) b = foo (1) # Return correct == b # Change __cmp__ function def cmp2 (self, other) Works: Return 1a__ cmp__ = cmp2 b. __cmp__ = cmp2 # Error picking a == b # Taxback (most recent call final): # file "", line 1, & lt; Module & gt; #TypeError: cmp2 () takes exactly 2 arguments (1 given)
no Do this
This will make your code smaller and difficult to maintain. The reason for this is difficult because correct is a sub-code to do this foo
:
class FunkyCmpFoo (foo): def __cmp__ (manually , Other): Return -1
& amp; C., & Amp; C. In this way, you know that all foo
compare equally, and compare all funkikkampu
s similarly. If you do not, then you will eventually compare a modified foo
with an original foo
, and you will be punished for raising yourself deeply.
I'm not sure that I should say this, but, by making my own:
funcType = type (foo.cd_c__) # Optionally: import New cmp2 = new.instancemethod (fenc, a, foo) a .__ cmp__ = funcType (cmp2, a, foo) b .__ cmp__ = funcType (cmp2, b, foo)
I can think of a good reason, and this is that if your arcanemy has to debug the code. In fact, I can think of some very interesting things in mind (you can think of sys at least all numbers too .maxint Like how to compare?). Besides, this is a nightmare.
Comments
Post a Comment