Unification of Methods and Functions

David MacQuigg dmq at gain.com
Sun May 30 19:42:44 EDT 2004


On 30 May 2004 10:51:44 GMT, Duncan Booth <me at privacy.net> wrote:

>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:

I'm not sure what this modification is intended to do, but assuming it
must work with multiple subclasses of OffsetRectangle, I would write
the example as follows:

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)    
    frmCenterAndSize = staticmethod(fromCenterAndSize)

class Rect1(OffsetRectangle): pass
class Rect2(OffsetRectangle): pass
class Rect3(OffsetRectangle): pass

for cls in Rect1, Rect2, Rect3, Rectangle:
    print OffsetRectangle.fromCenterAndSize(cls, 5, 10, 10, 10)

On the other hand, if you don't want to use the specific method from
OffsetRectangle, but you want the method to be chosen from the same
class as the class being instantiated, the last line would be:

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

I may be missing your intent.  If so, maybe you could show a more
complete example.

-- Dave




More information about the Python-list mailing list