How to pythonically have partially-mutually exclusive optional arguments?

后端 未结 7 2237
鱼传尺愫
鱼传尺愫 2021-02-13 18:04

As a simple example, take a class Ellipse that can return its properties such as area A, circumference C, major/minor axis a/b

7条回答
  •  失恋的感觉
    2021-02-13 18:52

    My proposal is focused on data encapsulation and code readability.

    a) Pick pair on unambigous measurements to represent ellipse internally

    class Ellipse(object):
        def __init__(a, b):
            self.a = a
            self.b = b
    

    b) Create family of properties to get desired metrics about ellipse

    class Ellipse(object):
        @property
        def area(self):
            return math.pi * self._x * self._b
    

    c) Create factory class / factory methods with unambigous names:

    class Ellipse(object):
        @classmethod
        def fromAreaAndCircumference(cls, area, circumference):
            # convert area and circumference to common format
            return cls(a, b)
    

    Sample usage:

    ellipse = Ellipse.fromLongAxisAndEccentricity(axis, eccentricity)
    assert ellipse.a == axis
    assert ellipse.eccentricity == eccentricity
    

提交回复
热议问题