Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass multiple parameters to class during initialization

Tags:

python

I have a requirement where things are all on scripts. No config file. Now i want to initialize a class using ~30 odd parameters. All objects will have different parameter values.

Can't figure out the best way to do it.

class doWorkWithItems():
    def __init__(self, dueX,dueY,dueZ,..):
        self.dueX = dueX
        ....
    def func1(self):
        work with above variables till object destroy.
worker1=doWorkWithItems(divX,divY,divZ,....)
like image 877
Abhishek Dave Avatar asked Aug 14 '15 08:08

Abhishek Dave


People also ask

How do you pass multiple parameters?

The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

How do you pass multiple parameters to a class in Python?

class doWorkWithItems(): def __init__(self, dueX,dueY,dueZ,..): self. dueX = dueX .... def func1(self): work with above variables till object destroy. worker1=doWorkWithItems(divX,divY,divZ,....)

How do you pass multiple arguments in Java?

The varargs functionality allows you to pass any number of arguments to a method. The method must be set up with the type of data and a variable name to hold the elements. You can add more parameters to the method, but the varargs statement must be the last one.

Can you have multiple init in Python?

Python does not support explicit multiple constructors, yet there are some ways using which the multiple constructors can be achieved. If multiple __init__ methods are written for the same class, then the latest one overwrites all the previous constructors. Look at the example below.


2 Answers

First, you've misunderstood the class declaration in Python.

This line:

class doWorkWithItems(dueX,dueY,dueZ,...):

should have the class/es to inherit from in the brackets. ie. class doWorkWithItems(object) or class doWorkWithItems(str). So your new class is trying to inherit from all those objects you've passed it.

When you want to pass initialisation parameters you just need to pass them within the __init__ function as you were doing.

class doWorkWithItems(object):
    def __init__(self, dueX,dueY,dueZ,..):

As for the best way to have a long list of arguments, Python has an operator for that, it's *. It unpacks a collection of items. It's commonly used with the name args and will allow for any amount of parameters to be passed in.

    def __init__(self, *args):
        self.args = args

It might be a good idea though, to store these values as a dictionary if they're for different uses, as that's easier to access than a plain list. You can turn the *args into a dictionary pretty easily if you pass every argument as a 2 element tuple like this:

    def __init__(self, *args):
        try:
             self.args = dict(args)
        except TypeError:
             #What to do if invalid parameters are passed

    ...

    obj = doWorkWithItems( ("Name", "John"), ("Age", 45), ("Occupation", "Professional Example"), )
    obj.args
    >>> {'Age': 45, 'Name': 'John', 'Occupation': 'Professional Example'}

But there is a better approach you could do if you pass parameters in a dictionary:

    def __init__(self, params):
        self.name = params.get('name')
        self.age = params.get('age')
        self.occupation = params.get('occupation')

The .get method will return a key from a dictionary, but if no key is found it will return None. This way all your class's variables can be created even if they're unspecified in parameters, they'll just be set to None. You don't need to access all the attributes through a dictionary, and it handles errors as long as you are passing a dictionary.

like image 92
SuperBiasedMan Avatar answered Sep 18 '22 22:09

SuperBiasedMan


If you want use a function that gets two parameters in a class. You can use my simple code:

class my_class:
  variable = "0"
  def function(self):
      print("sample function in class!!")
  a = 0
  b = 0
  def sum(self, a , b):
      print(a + b)

sample_object = my_class()

sample_object.sum(25,60)
like image 32
mfathi Avatar answered Sep 19 '22 22:09

mfathi