2

I wanted to write a class function which takes Signal object as a parameter and returns its copy. Then I wanted to overload this function with an instance function that returns copy of self argument. I have a following code:

@classmethod
def copy(cls, arg):
    if not isinstance(arg, Signal):
        raise ValueError("Argument must be of type Signal")
    result = Signal()
    result.framerate = arg.framerate
    return result

def copy(self):
    return FragmentsSignal.copy(self)

and

Signal1 = Signal(100)
Signal2 = signal1.copy()

But after calling the function copy my code goes into infinite recursive loop and throws name of this site as an exception. My questions are:

  1. Do I properly use python function overloading mechanism?

  2. How can I pass *this argument to a class function within my class?

IFeel3
  • 167
  • 1
  • 13
  • Is framerate the only Signal attribute? And do you want it to copy just one attribute (if there would be more in future) or all of them? – Nf4r Nov 24 '16 at 19:27
  • No, it isn't. I simplified code to make the problem clearer. – IFeel3 Nov 24 '16 at 19:29

1 Answers1

1

Do I properly use python function overloading mechanism?

You can't have two functions with the same name; Python does not support overloading based on the types of the arguments. The definition of the second function will override that of the first.

In essence you're calling the non classmethod function copy over and over again. You'll need to rename one of these in order to get it to work effectively.

How can I pass *this argument to a class function within my class?

I'm guessing you mean self here; passing self to another function is done as with any other arg (as you did FragmentsSignal.copy(self)). Your issue is that you're getting stumped by the recursion caused by the similar names.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • That's fair enough. Thank you :) – IFeel3 Nov 24 '16 at 19:32
  • 1
    Technically you can support overloading via argument type, with [`functools.singledsipatch`](https://docs.python.org/3/library/functools.html#functools.singledispatch) (although it takes a little [work](http://stackoverflow.com/a/24602374) to persuade it to do something useful with methods). But +1 anyway, since I'm being pedantic and your answer is the one OP needs :-) – Zero Piraeus Nov 24 '16 at 19:35