Unification of Methods and Functions

David MacQuigg dmq at gain.com
Mon May 24 19:17:59 EDT 2004


On Mon, 24 May 2004 14:10:44 +1200, Greg Ewing
<greg at cosc.canterbury.ac.nz> wrote:

>David MacQuigg wrote:
>> The need for static methods
>> will arise when the student first writes a method that needs to work
>> without a current instance.
>
>But why would he need such a method, as opposed to
>a plain function?

It may be that the method/function he has written fits most naturally
in a particular class.  This is for the programmer to decide, and we
should assume he knows his program structure better than we do.

class Bag:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
        
    def load(infile):
        strng = infile.read()
        exec( 'bag = Bag(\n' + strng + ')' )
        return bag
    load = staticmethod(load)

The load method is unique to Bags, and it belongs
in the Bag class.  To me this is a more fundamental consideration than
whether or not the method uses instance variables.

Distinguishing methods by whether or not they use instance variables
seems about like distinguishing them by whether or not they use global
variables.  We wouldn't want to move all "global methods" outside
their classes, just because of some quirk in the syntax required it.

-- Dave




More information about the Python-list mailing list