Declare Default Values for Mutable Types in Python
Python
If you want to specify a default for a function argument of an immutable type in Python, you assign the default in the function declaration.
You can’t assign a default value for an immutable type in this way. Instead, you can assign a default value None
and check for this inside the function - if the passed-in argument is None
, then assign a default:
#!/usr/bin/env python3
class Node:
def __init__(self, children: dict=None, is_end=False, text=''):
# If a dict is passed in, set self.children to this, otherwise
# set it to an empty dict.
self.children = children if children else dict()
self.is_end = is_end
self.text = text
def print(self):
print("is_end: {}, text: {}".format(self.is_end, self.text))
for key in self.children:
print("Key: {} Value: {}".format(key, self.children[key]))
def main():
a = Node()
b = Node({'a': 'value'}, True, 'hello!')
a.print()
b.print()
if __name__ == '__main__':
main()
comments powered by Disqus