Is it better to use class variables or pass parameters?
Eric Brunel
eric_brunel at despammed.com
Thu Mar 16 03:25:38 EST 2006
On 15 Mar 2006 15:04:19 -0800, Derek Basch <dbasch at yahoo.com> wrote:
> One more question everybody. Say you have a class that performs a
> series of evaluations on several strings of peptides.
Errr..., no? A class does not perform some operations. A class is a
template for objects. What are your objects? If you had a class Peptide
for example (I'm guessing here; I'm not exactly fluent in this domain), I
would have understood. But what you're describing here is not a class;
it's just a set of functions.
> Heres the class:
>
> class PeptideEvaluator:
>
> def evaluate(self, peptide):
> peptide_name = peptide + "Rules!"
> result1 = self.test1(peptide, peptide_name)
> result2 = self.test2(peptide, peptide_name)
> result3 = self.test3(peptide, peptide_name)
>
> def test1(self, peptide, peptide_name):
> f = open(peptide_name + ".txt", "w")
> f.write(peptide)
> f.close()
>
> def test2(self, peptide, peptide_name):
> f = open(peptide_name + ".txt", "w")
> f.write(peptide)
> f.close()
>
> def test3(self, peptide, peptide_name):
> f = open(peptide_name + ".txt", "w")
> f.write(peptide)
> f.close()
>
> So, you instantiate a class called "PeptideEvaluator" and pass in each
> string to its "evaluate" method. Now you have to repeatedly pass the
> peptide and peptide_name to each function. According to what everyone
> has said declaring them as class variables is bad because they are not
> related to the state of the "PeptideEvaluator". How can I avoid having
> to pass the same parameters all over a class? I can';t quite seem to
> wrap my head around this one.
QED: this "class" has no need at all for attributes, and does not even
have a constructor. This is usually a strong signal that what you're doing
is wrong. Just turn this class into a module containing functions. Or put
these methods into another class (the Peptide class may be a good
candidate if you have one; "evaluating" a peptide seems to be an operation
that you do on peptides).
HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
More information about the Python-list
mailing list