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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With