[Tutor] Re: How do you share a method (function) among several objects?

Xif xifxif at gmail.com
Sun Feb 27 19:20:19 CET 2005

Javier Ruere wrote:

> Xif wrote:
>> Hello
>> There are several different objects. However, they all share the same
>> function.
>> Since they are not the same or similar, it's not logical to use a
>> common superclass.
>> So I'm asking, what's a good way to allow those objects to share that
>> function?
>> The best solution I've found so far is to put that function in a
>> module, and have all objects import and use it. But I doubt that's a
>> good use-case for modules; writing and importing a module that contains
>> just a single function seems like an abuse.
>> Thanks,
>> Xif
>   Could you give an example?
> Javier
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> +++++++++++++++++++++++++++++++++++++++++++
> This Mail Was Scanned By Mail-seCure System
> at the Tel-Aviv University CC.
Sure, I can describe my particular case.

It's a program that retrieves / updates Microsoft Excel spreadsheet data.

There are two major classes:

1) an Excel class, that represents of the whole Excel program
2) a Cells class, that abstracts retrieval  and editing of cells.

Both classes use a function called getCells() as part of their 
__getitem__() methods.

getCells() parses the __getitem__() call arguments, and returns an 
iterator over the appropriate cells.

The difference between the 2 classes is that a Cells instance just 
converts the generator into a list and returns it:

return list(getCells(self.sheet, cells))

while an Excel instance returns the values of the cells:

return [cell.Value for cell in getCells(self.sheet, cells)]

As you can see, both use the getCells() function.

So my question is, where is the best way to put it so instances of both 
classes can use it?


More information about the Tutor mailing list