How to Pass a Default Argument Value of an Instance Member to a Method

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!

Difficulties to assign default value to a parameter of a function

I don't think that is possible. The default value is inserted at the calling site, and therefore needs to be public, see also
Access control in swift 4.

A possible workaround would be to make the parameter optional,
and substitute nil by the default value locally:

class Foo {
private static let DefaultValue = 10

public func doTask(amount: Int? = nil) {
let amount = amount ?? Foo.DefaultValue
// ...
}
}

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)
}

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 set a default parameter of a class member function as another member function within the same class in Python

The default value is evaluated once, when the function is defined, not every time it's called. So it can't refer to other parameters or other dynamic data.

You'll need to assign it in the function.

def bar(self, func = None):
if func is None:
func = self.foo
func()
print('bar')

Python Instance Variable as Default Parameter

The short answer to your question is no, you cannot eliminate the if statement, because Python examines the signature only once, and so the default is shared across all calls. Consider, for example:

def addit(x, L=[]):
L.append(x)
return L

Versus:

def addit(x,L=None):
if L is None:
L=[]
L.append(x)
return L

These two functions, though they look identical, actually have completely different behavior; in the first one, the default value of L is shared between invocations so that addit(1) followed by addit(2) will return, in the first case, two objects that are actually point to the same underlying object and that have a value of [1,2], while it the second case it will return two separate objects, [1] and [2].

The only recommendation I have for you, then, is to use a default of None simply because that is the standard convention for parameters that have not been specified, but to continue using an if check, because using as a default value some existing object will have subtly different (usually wrong) behavior.

How to use a member variable as a default argument in C++?

Default argument expressions for a member function can only depend on things that are in class or global scope. The default argument also has to be specified in the method's declaration (i.e. in the header file).

To get around this, you need 2 overloads of your MoveTo method. One that takes 1 argument, and another that takes 2 arguments. The method taking 1 argument calls the other method, passing along the value that you consider as the default.

void Object::MoveTo(double speed)
{
MoveTo(speed, initPos);
}

void Object::MoveTo(double speed, Point position)
{
// Everything is done here.
}

Note that when you make MoveTo(double) call MoveTo(double, Point), it allows you to write the implementation of MoveTo only once, thereby respecting the DRY principle.

How to pass reference of a class parameter value to a function default argument value within the same class

Use another default value and then check:

def validate_subnetmask(self, input_subnetmask=None):
if input_subnetmask is None:
input_subnetmask = self.subnet_mask

even shorter thanks to @CamiEQ:

def validate_subnetmask(self, input_subnetmask=None):
input_subnetmask = input_subnetmask or self.subnet_mask


Related Topics



Leave a reply



Submit