mutually exclusive arguments to a constructor

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Dec 30 17:21:09 EST 2011


On Fri, 30 Dec 2011 21:18:29 +0000, Jason Friedman wrote:

> class azimuth:
>     def __init__(self, bearing, heading):

It is conventional, and recommended, to use an initial capital letter for 
classes. (Yes, Python built-ins violate that rule, and indeed so do some 
non-built-ins.) See PEP 8 for the recommended style guide.


[...]
>     @staticmethod
>     def getBearingInstance(bearing):
>         return azimuth(bearing, None)
>     @staticmethod
>     def getHeadingInstance(heading):
>         return azimuth(None, heading)

In this case, you should use classmethod rather than staticmethod and 
avoid hard-coding the class:

    @classmethod
    def getBearingInstance(cls, bearing):
        return cls(bearing, None)

That way subclassing will work correctly:


class MyAzimuth(azimuth):
    pass

angle = MyAzimuth.getBearingInstance("N24d30mE")

will return a MyAzimuth instance instead of an azimuth instance.



-- 
Steven



More information about the Python-list mailing list