[Tutor] class initialization with a lot of parameters

Alan Gauld alan.gauld at btinternet.com
Wed Nov 11 19:19:17 CET 2009


"C.T. Matsumoto" <c.t.matsumoto at gmail.com> wrote

> The Table object you described I find more complicated if each table 
> stands
> on its own it is decoupled from its compare partner. I suppose a function
> that pairs the tables, feeding a Table object to its partner 
> Table.compare
> method.

Kind of.

Think about something simpler. Like numbers.

when we do

if number1 == number2:

what we actually do in Python is

if number1.__eq__(number2):


In other words we call the special method __eq__() of number1 passing
in number2.

So == is actually a method of the object on the left hand side.

Similarly if you want to compare tables for equality you can define a class
Table and provide an __eq__() method and you will be able to write

if table1 == table2

and it will work.

And your __eq__() method can be a completely bespoke algorithm for
determining what equality means for your table class. It could mean that
every value of every field is the same or it could mean that the 3rd field
in number1 is twice the value of the 5th field in number2. Its entirely up 
to you.
But the ability to compare two things of the same class is an operation
of the class.

The same applies to >, <, >=, <= etc. They all have special methods
that you can override to make object comparisons work the way you
want them to.

> Hmm ... This has got to sink in.

Its quite a big jump from traditional programming but one of the areas
where OOP can dramatically simplify your code.  Once you build the
objects to act like the built in types your code that uses those objects
suddenly becomes much more readable

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list