<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head>
<body bgcolor="#FFFFFF" text="#000000">
Le 26/04/17 à 19:46, Mike Miller a écrit :<br>
<blockquote
cite="mid:626ce4d3-0407-70af-44ba-d2ace007eb72@mgmiller.net"
type="cite">
<br>
On 2017-04-26 04:12, Brice PARENT wrote:
<br>
<blockquote type="cite">Why not simply do this :
<br>
<br>
class MyClass:
<br>
def _set_multiple(self, **kwargs):
<br>
for key, value in kwargs.items():
<br>
setattr(self, key, value)
<br>
<br>
def __init__(self, a, b, c):
<br>
self._set_multiple(a=a, b=b, c=c)
<br>
</blockquote>
<br>
If the goal is to not have to type out argument names three times
(in DRY fashion), this doesn't quite fit the bill.
<br>
<br>
-Mike
<br>
<br>
</blockquote>
You still save some typing (no need for <i>self.</i> for every
assignment), and a lot of vertical space.<br>
<br>
Also, it allows you to use any dict (like **kwargs) as well as doing
very common things like :<br>
<br>
<tt>class MyClass:
</tt><tt><br>
</tt><tt> def _set_multiple(self, **kwargs):
</tt><tt><br>
</tt><tt> for key, value in kwargs.items():
</tt><tt><br>
</tt><tt> setattr(self, key, value)
</tt><tt><br>
</tt><tt>
</tt><tt><br>
</tt><tt> def __init__(self, a, b, c):
</tt><tt><br>
</tt><tt> self._set_multiple(a=a, _b=b)</tt><br>
<br>
which is equivalent to the following really common pattern :<br>
<br>
<tt>class MyClass:
</tt><tt><br>
</tt><tt>
def __init__(self, a, b, c):
</tt><tt><br>
</tt><tt>
self.a = a</tt><tt><br>
</tt><tt> self._b = b</tt><br>
<br>
(well, I didn't try it, but it should work)<br>
This means your public API (the signature of the constructor here)
has no incidence on the way the class works on the inside. Meaning
an attribute can become a property, which is something that occurs
from time to time, and you just need to update your constructor (<tt>self._set_multiple(a=a,
b=b)</tt> becomes <tt>self._set_multiple(a=a, _b=b)</tt>) and
you're done. <br>
And if at some point your community doesn't think "a" is a good name
for your variable, you can update it to something every user will
understand without any significant change to your class (<tt>self._set_multiple(a=way_better,
_b=b)</tt>). <br>
<br>
-Brice<br>
<br>
</body>
</html>