JavaScript
x
12
12
1
class Disease:
2
def __init__(self, category, name, nicknames, sx, *labs, **inheritance):
3
self.category = category
4
self.name = name
5
self.nicknames = nicknames
6
self.sx = sx
7
self.labs = labs #incl. vitals
8
self.inheritance = inheritance
9
def printLabs(self):
10
for item in self.labs:
11
print(item)
12
This works fine, but when I try to initialize a Disease with three optional values, or with the optional value in the middle (ie nicknames), it doesn’t work.
Is there any way around these issues?
Advertisement
Answer
To make a value sometimes optional, you either have to pull it from *labs
or **inheritance
, or provide a default value such as:
JavaScript
1
3
1
class Disease:
2
def __init__(self, category, name, nicknames=None, sx=None, *labs, **inheritance):
3
Now, if the user does not provide a value for nicknames, or sx, they remain as None.
Note: Optional (default) arguments like this must be at the end of the function declaration – meaning you cannot do something like def __init__(self, category, name=None, nicknames, sx, *labs, **inheritance)
because after name
, all arguments must have default values or else you’ll get a a SyntaxError
.