IFeel3
IFeel3

Reputation: 305

Passing self object to function that requires this type

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?

Upvotes: 2

Views: 1064

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160417

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.

Upvotes: 1

Related Questions