Using self.xxxx as a default parameter - Python
larsmans answered your first question
For your second question, can you simply look before you leap to avoid recursion?
def makeList(self, aNode=None):
if aNode is None:
aNode = self.root
treeaslist = [aNode.data]
if aNode.lChild:
treeaslist.extend(self.makeList(aNode.lChild))
if aNode.rChild:
treeaslist.extend(self.makeList(aNode.rChild))
return treeaslist
Using self.* as default value for a method
Use a default of None
and detect that.
def save_file(self, outputfilename=None):
if outputfilename is None:
outputfilename = self.image_filename
self.file.read(outputfilename)
....
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
Evaluating self inside function
Function default values are evaluated when the function is defined, not every time the function is called without the necessary argument. As such, self
is just a name, not the object invoking the function.
Instead, you just need a sentinel, which is a value that you can use at runtime to determine if an argument was passed. Typically, you can use None
, though when None
is a valid argument, you'll need to choose a different value.
def func(self, test=None):
if test is None:
test = self.text
return test
How to use default value for input, which is a member of self (Python)?
Function defaults are determined when the class is built, not when the method is called. At that time there are no instances available to take a default from, no.
You'll have to use a sentinel default here, using None
as sentinel as you have done the most common solution used.
If it should be possible to specify None
as a value for n
, use a different singleton object:
_sentinel = object()
class C:
def __init__(self, x):
self.x = x
def f(self, n=_sentinel):
if n is _sentinel:
n = self.x
class overwrite __init__ default parameter
why don't you just provide a different argument when you construct an instance of the class:
foo = Foo(dir='something else')
btw: dir
is a python built-in and therefore not the best choice as variable name.
if you want the default changed, you can inherit indeed:
class MyFoo(Foo):
def __init__(self, d='somethig else'):
super().__init__(d=d)
Order of default and non-default arguments
Well, range
is C code which can do this slightly better. Anyways, you can do this:
def range(start, stop=None):
if stop is None: # only one arg, treat stop as start ...
stop = start
start = 0
...
and document the function accordingly.
Using the length of a parameter array as the default value of another parameter of the same function
Based on the answer provided by @NPE in Function with dependent preset arguments, an alternative to using -1
or (better) None
as sentinel values is using an object (a named object?) which can be used even if None
is a valid value of the function. For example:
default = object()
def function(a, start = 0, end = default):
if end is default: end = (len(a) - 1)
return start, end
allows a call like: function([1,2,3,4])
which returns (0, 3)
I personally find this solution quite convenient, at least for my own purpose
Edit: Maybe the code is even more readable if we use last
instead of default
:
last = object()
def function(a, start = 0, end = last):
if end is last: end = (len(a) - 1)
return start, end
Related Topics
Fix Not Load Dynamic Library for Tensorflow Gpu
How to Access a Function Inside a Function
Download and Save PDF File with Python Requests Module
Convert Dictionary Entries into Variables
Iso to Datetime Object: 'Z' Is a Bad Directive
Weighted Choice Short and Simple
Find Substring in String But Only If Whole Words
How to Rotate a Matplotlib Plot Through 90 Degrees
Python Requests.Get Always Get 404
Openpyxl 1.8.5: Reading the Result of a Formula Typed in a Cell Using Openpyxl
Most Efficient Way to Search the Last X Lines of a File
For Loops and Iterating Through Lists
Generating Sublists Using Multiplication ( * ) Unexpected Behavior
Screenshot of Inactive Window Printwindow + Win32Gui
Weird Behavior: Lambda Inside List Comprehension
Anyone Know of a Good Python Based Web Crawler That I Could Use