Reputation: 86
I am making an object-oriented text adventure engine code, and my main goal is to make it user-friendly, but powerful. One of the classes in the code currently takes 15 arguments. However, in each instance of the class, only a few of the arguments are actually defined and many of them end up being left blank.
For the purpose of creating more concise code and also to make the experience of using the engine more user-friendly, I am wondering if there is any way to make some of the parameters in the class optional to fill out. The goal of this would be that when you create an instance of the said class, you would only need to define the arguments that you need for that specific instance, instead of having to also define all the other arguments as valueless.
In other words, I am wondering if this is possible:
class sampleClass:
def __init__(self, arg1, optional1)
self.arg1 = arg1
self.optional1 = optional1
var = sampleClass(value)
var = sampleClass(value2, value3)
In the above case, the "optional1" variable can be defined or can be left blank.
I have also looked into the posts on *args and **kwargs on this site, and it seems to me that both arguments can each take multiple values, but none of them have the option to take no values.
In conclusion, is it possible to have completely optional arguments in a python class which can be defined or left blank and no error message will result?
Also, sorry for anything wrong I have done in this post. This is my first question on Stack Overflow, so I am new to the site. Please tell me if there is anything I can improve on to ask better questions.
Upvotes: 2
Views: 10838
Reputation: 371
Try this: Use of *args and **kwargs
**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.
def manyArgs(*arg):
print("Was called with ", len(arg), " arguments: ", arg)
def main():
manyArgs()
if __name__ == "__main__":
main()
if i run this without any arguments it prints the following line:
Was called with 0 arguments: ()
Upvotes: 1
Reputation: 531135
I have also looked into the posts on *args and **kwargs on this site, and it seems to me that both arguments can each take multiple values, but none of them have the option to take no values.
That's not correct.
>>> def f(*args, **kwargs):
... print("Args: %r" % (args,))
... print("Kwargs: %r" % (kwargs,))
...
>>> f()
Args: ()
Kwargs: {}
Upvotes: 1
Reputation: 599600
A class init method is just the same as any other function, and its arguments can default to None.
def __init__(self, arg1, optional1=None):
Upvotes: 2