[Tutor] question about class

Lie Ryan lie.1296 at gmail.com
Wed Jun 10 19:53:27 CEST 2009


Vincent Davis wrote:
> Thanks again for the help, A little followup.
> For my applicant class I have a few initial values that need to be set
> but I what to choose the value (actually the calculation to set the
> value) for each applicant (instance?)
> Here is the start of my Applicant Class
> 
> class Applicant(object):
>       "quality is refers to the quality of the Applicant
>           observe refers to the accuracy of which they assess the
> quality of the school"
>       def __init__(self, quality = 0, observe = 0):
>               self. quality = quality
>               self. observe = observe
>       def Quality(self, mean, sd):
>               print self,
>               self.quality = normalvariate(mean, sd)
>               print "--> %s" % self
>      def Observe(self, mean, sd):
>               print self,
>               self. observe = normalvariate(mean, sd)
>               print "--> %s" % self

The problem with that approach is that repeated calls to Quality and
Observe would change the value of self.quality and self.observe and it
will be therefore unnecessary (and dangerous) to call
self.Quality/Observe again in the future

Usually I'd go with something like this:

class Applicant(object):
    def __init__(self, quality, observe):
        self.quality = quality
        self.observe = observe
    def norm_quality(self, mean, sd):
        return normalvariate(mean, sd, self.quality)
    def norm_observe(self, mean, sd):
        return normalvariate(mean, sd, self.observe)

Additionally-- although it is a matter of style --instead of passing
mean and sd to norm_quality, I'd use functools.partial with
normalvariate, mean, and sd. Then since they now don't take parameters
they can then be easily turned into property using decorator.

> Or I could I guess do it this way, Is this better? I will only be
> setting the quality and observe values once for each instance.
> 
> class Applicant(object):
>       "quality is refers to the quality of the Applicant
>          observe refers to the accuracy of which they assess the
> quality of the school"
>       def __init__(self, mquality = 0, sdquality = 0, mobserve = 0,
> sdobserve = 0):
>               self. quality = normalvariate(mquality, sdquality)
>               self. observe = normalvariate(mobserve, sdobserve)

That approach is fine as well, however it wouldn't be much different
than using a tuple.



More information about the Tutor mailing list