Adam Greenhall
Adam Greenhall

Reputation: 5058

python class with many attributes

I am trying to create a class with lots of attributes (about 10). Is there a prettier (more Pythonic) way to initiate the class than:

class myClass:
def __init__(self,atributeA,atributeB,atributeC)
   self.atributeA=atributeA
   self.atributeB=atributeB
   self.atributeC=atributeC

and is there a better way to make a class instance than

thisInstance=myClass(valueA,valueB,valueC)

Upvotes: 5

Views: 3325

Answers (4)

Rosh Oxymoron
Rosh Oxymoron

Reputation: 21065

You can use the following for the initialisation.

def __init__(self, attributeA, attributeB, attributeC)
    vars(self).update(locals())

Upvotes: 2

Josh Smeaton
Josh Smeaton

Reputation: 48730

You can use a dirty method too:

def __init__(self, *args, **kwargs):
    self.__dict__.update(kwargs)


d = {"attributeA": "a", "attributeB": "b"}
c = MyClass(**d)

Note though, that any property within the dict that has the same name as an important property of your class will overwrite that important property.

Edit: In case it's not understood, by dirty I mean don't do this unless you have a fantastic reason, and your class can not be misused by other people!

Upvotes: 2

Peter C
Peter C

Reputation: 6307

Well, you could use keyword arguments. It would be as simple as:

thisInstance=myClass(atributeA=valueA, atributeB=valueB, atributeC=valueC)

One of the advantages of this is that you can pass the values in any order you want.

You don't even have to modify the class definition at all.

Upvotes: 3

joaquin
joaquin

Reputation: 85693

you could use *args or **kwargs and send a tuple or dictionary with your parameters

Upvotes: 0

Related Questions