Saturday 15 June 2013

python - Overload a method with a function at runtime -


OK, I'll already accept that this is a big villain and I can definitely apply it better I am It's just a hysterical curiosity that has come to me to find out how I can do it.

  class some class (object): def __init __ (self): def __ (self, agre): self. (String): Print string SomeClass (). Overloaded ("test string")  

This returns a parameter error because I'm only supplying overloaded (with two arguments instead of two) to tell the interpreter something The magic is that it is now a class method (I tried to decorate it with classmate, I have always considered it as its purpose ??)

Do not worry about self-parameters, the function is already available Is from the local area.

  class Some object (object): def __int_ (self): def __ (arg): self.bar (arg) self.foo = __ def foo (self, arg): print "Foo", arg def bar (self, arg): print "bar", arg some class () Foo ("Cheese") # Print "Bar Object"  

When creating an example ( __ new __ , IIRC, but before that __ init__ ) Python automatically binds all the methods to supply the example as the first argument. If you are adding a method later, then you have to manually supply the example manually. As you define work with self , you do not need to pass it again.

Python's new module is not a solution, it has been downgraded since 2.6. If you want to create a "real" example method, then partial decorator has to do it like this:

  import, some square (object): def __init __ (self): def __ ( Self, Arg): Self. Bar (Arg) itself Fu = "False" (self, AGR): print "AFU", AGR DRF Bar (self, AGR): print "bar", arg some class) .Fu ("cheese") # print " Bar object " 

No comments:

Post a Comment