Unification of Methods and Functions

Duncan Booth me at privacy.net
Sun May 30 06:51:44 EDT 2004


David MacQuigg <dmq at gain.com> wrote in 
news:qathb0ltkjpafa01ica9gdglnohptuuo3n at 4ax.com:

>>Ok, I'll try and give you a couple of examples, feel free to tear them 
>>apart. The most obvious one is to write factory methods:
> 
> I like these examples, and I think they will fit nicely into the
> teaching sequence -- Spam and Foo, Animals_1, Animals_2, then some
> real programs.  I would change the classmethods to staticmethods,
> however, and avoid the need to teach classmethods.  This would make
> your calls look like:
> 
> print Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4)
>   -- or if you prefer a short alias --
> print CS(Rectangle, 10, 10, 3, 4)
> 

So how do you handle the case where you need to override one of the factory 
methods in a subclass?

e.g. Rather contortedly:

class OffsetRectangle(Rectangle):
    '''A rectangle where the 'center' is actually half way up
       the left edge'''
    def fromCenterAndSize(cls, cx, cy, width, height):
        self = cls()
        self.moveTo(cx+width/2.0, cy)
        self.resize(width, height)
        return self
    fromCenterAndSize = classmethod(fromCenterAndSize)    

print OffsetRectangle.fromCenterAndSize(5, 10, 10, 10)



More information about the Python-list mailing list