14

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,....)
3
  • 1
    What is your exact question? Commented Aug 14, 2015 at 8:45
  • Consider using arbitrary argument list. Commented Aug 14, 2015 at 8:52
  • My question is 1) when i want a class object i have to pass ~30-40 different parameters. (no need of dictionary here, they are unrelated). 2) any way to get rid of this long line worker1=doWorkWithItems(divX,divY,divZ,....) Commented Aug 20, 2015 at 7:47

5 Answers 5

35

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.

Sign up to request clarification or add additional context in comments.

5 Comments

But in my case, i don't want 1) Inheritance ( not complicating) 2) dict type as records are unrelated.
I want to handle obj = doWorkWithItems( "Alex D", "John, J", 45,...... and so on ) How to avoid calling this thousands of time? any idea would be of great help.
What form does the data take? You could technically use *args and then set data with name = args[0]; clientName = args[1] but you'd need to handle what happens if an insufficient amount of parameters are provided.
data is mostly config params. i must send the proper order. This is handled. only issue is the creation of object. how to pass 20-30 parameters to constructor every time. Say i am dealing with thousands of objects.
3
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,....)

If you put something in parentheses behind the class name, it's inheritance. The arguments should appear in __init__() as you wrote.

1 Comment

Thanks @SuperBiasedMan for solving my issue. Yes i am yet to learn python. Thanks all for helping me out. This is a great help.
3

Initialization of an object in python is done using the constructor method which is: init method so whatever arguments you are passing to make an object out of that class is going to init method. So, only that method should have those parameters. Those should not be present along with the class name.
Python uses that for inheritance purpose. Read this for more on inheritance.
For cleaner code i would suggest using *args and **kwargs

Comments

1

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)

Comments

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

1 Comment

Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.