[Tutor] Classes that do operator overloading
Alan Gauld
alan.gauld at btinternet.com
Sat Nov 7 15:06:15 CET 2009
"C.T. Matsumoto" <tmatsumoto at gmx.net> wrote
> class Foo: # the book says this is a class header
> pass
Hmm, that's pretty dubious usage of header in my view.
Its the class definition and there is nothing "header" about it.
> As for my question it looks like the convention is if a class only has
> operator overloading then the class receives a lowercase class name.
Hugo and Tim have answered that. Pep 8 says no, but local
standards may over-rule that.
It is worth pointing out however that classes which only have
operator overloads in them are pretty rare! Especially ones
that don't inherit from an existing type or class.
The Indexer example is not very typical, a pseudo list
where the content that is apparently always twice the index.
I can see it being used to save space where the
alternative would be a list comprehension like:
myIndexer = [2*n for n in range(bugnum)]
It would also guarantee that you never had an index out of range.
But personally even there I'd generalise it by passing in a function
so that the Indexer could return any function of the index:
class Indexer:
def __init__(self, func = lambda n: n):
self.func = func
def __getitem__(self, index)
return self.func(index)
doubles = Indexer(lambda n: n*2)
squares = Indexer(lambda n: n*n)
plus3s = Indexer(lambda n: n+3)
etc.
But its certainly not exactly a typical scenario.
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list