[Tutor] question about class

A.T.Hofkamp a.t.hofkamp at tue.nl
Tue Jun 9 09:23:57 CEST 2009


Vincent Davis wrote:
> Accidentally sent I have added the rest
> (by the way I refrain from using the terms attribute, method,.... as I
> will likely miss use them)
> 
>> I am reading several tutorials about classes and trying to figure out
>> how to apply it to my project. I have a working program that basically
>> matches up applicants and schools. Schools and applicants have and
>> "true" quality and an "observed" quality. Then there is an algorithm
>> that matches them up. Right now I do this all with lists which works
>> ok but I would like to try using classes.

sounds like a good plan.

>> Questions
>> 1, does it make seens to have a applicant and a schools class (based
>> on this brief explanation)

Most likely, yes.

>> 2, is it possible to have a class for the algorithm that will modify
>> values in the applicant and schools class
> for example applicant.matched = 4 and school.matched = 343 meaning
> applicant 343 is matched to school 4

I don't understand the example, but that may not matter.

Yes it is possible to make an object of your algorithm.
However, if you have exactly one such algorithm, there is little point imho to 
wrap it into a class.

You may also want to wrap the result in an object.
(but your approach of modifying the applicant or school objects is fine too!)


> 3, is I have a value set in a class applicant.foo = 5 and I what to
> use a (method?) in the class to change this, what is the right way to
> do this?

If you want to make a setter, below is an example.

class X(object):
   """
   Example class with a value.

   @ivar v: Value of the object.
   """
   def __init__(self, v):
     self.v = v

   def set_v(self, new_v):
     self.v = new_v

my_x = X(5)
my_x.set_v(4)

is the way to use a method for setting a value.

However, Python discourages the use of such methods, since you are mostly 
adding boiler plate code without gaining anything.


So instead, I'd suggest to forget about getters and setters, drop the 
X.set_v() method, and do

my_x = X(5)
my_x.v = 4

which is cleaner and equally precise in your intention.


Albert


More information about the Tutor mailing list