开发者

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.a开发者_如何学运维tributeB=atributeB
   self.atributeC=atributeC

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

thisInstance=myClass(valueA,valueB,valueC)


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.


You can use the following for the initialisation.

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


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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜