Using a Property as a Default Parameter Value for a Method in the Same Class

Using a property as a default parameter value for a method in the same class

I don't think you're doing anything wrong.

The language specification only says that a default parameter should come before non-default parameters (p169), and that the default value is defined by an expression (p637).

It does not say what that expression is allowed to reference. It seems like it is not allowed to reference the instance on which you are calling the method, i.e., self, which seems like it would be necessary to reference self.niceAnimal.

As a workaround, you could define the default parameter as an optional with a default value of nil, and then set the actual value with an "if let" that references the member variable in the default case, like so:

 class animal {
var niceAnimal: Bool
var numberOfLegs: Int

init(numberOfLegs: Int, animalIsNice: Bool) {
self.numberOfLegs = numberOfLegs
self.niceAnimal = animalIsNice
}

func description(numberOfLegs: Int, animalIsNice: Bool? = nil) {
if let animalIsNice = animalIsNice ?? self.niceAnimal {
// print
}
}
}

How to use class property as a default parameter in Python?

If you are really hard-coding the default in __init__, you would be better off (ab)using a class attribute as the default.

class Class:
_param_default = True

def method(self, parameter=_param_default):
return parameter

del _param_default # Optional, but it's not really a class attribute

If this really should have an instance-specific default, you can't really make it any shorter. The method is defined before the instance is created, so you need to make the check at runtime.

class Class:

_sentinel = object()

def __init__(self):
self.property = True

def method(self, parameter=_sentinel):
if parameter is _sentinel:
parameter = self.property
return parameter

None is the more conventional sentinel, and you can use that in place of _sentinel if None isn't otherwise a valid argument to method.

Can I set up a default method argument with class property in PHP?

Yes, you have to do it this way. You cannot use a member value for the default argument value.

From the PHP manual on Function arguments: (emphasis mine)

A function may define C++-style default values for scalar arguments. […] PHP also allows the use of arrays and the special type NULL as default values. […] The default value must be a constant expression, not (for example) a variable, a class member or a function call. […] Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

How can I use the default parameter values of the constructor when there is no corresponding value to deserialise?

You could write a custom JsonConverter, alternatively make the constructor parameters for ImmutablePropertyStore be nullable and default their values to null. Then inside the ctor you can determine what the 'real' default value should be.

public ImmutablePropertyStore(bool? propertyA = null, bool? propertyB = null)
{
PropertyA = propertyA ?? true;
PropertyB = propertyB ?? false;
}

As you mentioned, the default values for a property type is used (null for nullable types) which is then converted to the correct 'real' value in the ctor.

The default values are not as apparent using this method but I'm not sure whether that will be an issue or not.

Instance member as default parameter

The reason is in different context visibility, the arguments context of interface function is external in relation to class declaration, so members are not visible, but nested function is declared inside class context, as other function body, so members are visible.

So the solution might be static, as already proposed, but it might have drawbacks (eg. for reference default members), so I recommend to use it only for constants.

The other possible solutions is below

func add(value: String, node: TrieNode?) { // no error
func _add(value: String, node: TrieNode? = root) { // in-context
var myNode = node
if myNode == nil {
myNode = root
}
if value.count == 0 {
node?.setEnd()
return
} else if myNode!.keys[String(value.first!)] == nil {
myNode!.keys[String(value.first!)] = TrieNode()
return add(value: String(value.dropFirst()), node: myNode!.keys[String(value.first!)])
} else {
return add(value: String(value.dropFirst()), node: myNode!.keys[String(value.first!)])
}
}
_add(value: value, node: node)
}

Does Java support default parameter values?

No, the structure you found is how Java handles it, (that is, with overloading instead of default parameters).

For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors)

If the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help.

This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.

How to pass a default argument value of an instance member to a method?

You can't really define this as the default value, since the default value is evaluated when the method is defined which is before any instances exist. The usual pattern is to do something like this instead:

class C:
def __init__(self, format):
self.format = format

def process(self, formatting=None):
if formatting is None:
formatting = self.format
print(formatting)

self.format will only be used if formatting is None.


To demonstrate the point of how default values work, see this example:

def mk_default():
print("mk_default has been called!")

def myfun(foo=mk_default()):
print("myfun has been called.")

print("about to test functions")
myfun("testing")
myfun("testing again")

And the output here:

mk_default has been called!
about to test functions
myfun has been called.
myfun has been called.

Notice how mk_default was called only once, and that happened before the function was ever called!



Related Topics



Leave a reply



Submit