Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have dynamic default arguments?

I'm trying to make a class where the user can modify member variables to change the default arguments of its member functions.

class Class
{
    public int Member;

    public void Method(int Argument = Member)
    {
        // This compiles fine, until I try to actually use
        // the method elsewhere in code!

        // "Error: need 'this' to access member Member"
    }
}

My workaround so far has been to use magic numbers, which obviously isn't ideal.

public void Method(int Argument = 123)
{
    int RealArgument;

    if (Argument == 123) RealArgument = Member;
    else RealArgument = Argument;
}

Is there a better way, or am I stuck with this "hack" solution?

like image 608
Maxpm Avatar asked Oct 10 '11 14:10

Maxpm


People also ask

Can we give all arguments as default argument in function?

So, it is optional during a call. If a value is provided, it will overwrite the default value. Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.

What is a mutable default argument?

Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

Can non-default argument follow default argument?

The Python “SyntaxError: non-default argument follows default argument” error is raised when you specify a default argument before a non-default argument. To solve this error, make sure that you arrange all the arguments in a function so that default arguments come after non-default arguments.


1 Answers

Yep, forget about the default argument.

class Class
{
    public int Member;

    public void Method(int Argument)
    {
        ...
    }

    public void Method()
    {
        Method(Member);
    }
}

No need for trickery here.

like image 58
Peter Alexander Avatar answered Sep 19 '22 03:09

Peter Alexander