Generic constructor in Python

Possible duplicate:
Assign arguments to the `self` function

Often I have constructors that look like this:

class Foo(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c 

I was wondering if there is a convenient way to code such constructors. Maybe something similar:

 class Foo(object): SOME_MACRO_LIKE_THINGY_THAT_SPECIFIES_THE_CONSTRUCTOR(a,b,c) 

which will behave exactly the same as the source code above.

What bothers me with the original version is that I have to write each instance variable of Foo three times (once as an argument, once as self.a and once again as the value for assigning self.a).

I believe this is not such a big deal, but it seems to me that the code will look more neat with fewer repetitions.

What is the python way to deal with this situation?

+4
source share
3 answers

This is strange, but you can use __slots__ to achieve this:

 class Base(object): def __init__(self, *args, **kw): for k,v in zip(self.__slots__, args): setattr(self, k, v) for k,v in kw.items(): setattr(self, k, v) class ChildA(Base): __slots__ = 'a', 'b', 'c' class ChildB(Base): __slots__ = 'x', 'y', 'z' 

You can also use the following technique to save yourself on typing when initializing classes with many arguments:

 def autoargs(l): self = l.pop('self') for k,v in l.items(): setattr(self, k, v) class Base(object): def __init__(self, a, b, c): autoargs(locals()) 

I hope I understand your question correctly.

+2
source

you can make Foo and all the rest as subclasses of the master class, i.e.

 class MasterObject(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c class Foo(MasterObject): def __init__(self,a,b,c): MasterObject.__init__(a,b,c) 
+2
source

you can do something like this

 class Foo(object): def __init__(self, **kw): self.__dict__.update(kw) del self.__dict__["self"] 

but then you must specify all instance variables every time you create an instance of the class. I think this makes the code more fragile. Since most people don't like fragile code, they stick with the explicit version.

You can write a macro for your editor to expand them, I suppose, but I don’t think that a very large amount of time was spent on this part, and not all classes want to save all the arguments in an instance.

0
source

Source: https://habr.com/ru/post/1447081/


All Articles