3

我想为我的模拟代码中使用的物理/数学量建立一个好的命名方案。考虑以下示例:

from math import *

class GaussianBeamIntensity(object):
    """
    Optical intensity profile of a Gaussian laser beam.
    """

    def __init__(self, intensity_at_waist_center, waist_radius, wavelength):
        """
        Arguments:

        *intensity_at_waist_center*: The optical intensity of the beam at the
            center of its waist in W/m^2 units.

        *waist_radius*: The radius of the beam waist in meters.

        *wavelength*: The wavelength of the laser beam in meters.

        """

        self.intensity_at_waist_center = intensity_at_waist_center
        self.waist_radius = waist_radius
        self.wavelength = wavelength
        self._calculate_auxiliary_quantities()

    def _calculate_auxiliary_quantities(self):
        # Shorthand notation
        w_0, lambda_ = self.waist_radius, self.wavelength

        self.rayleigh_range = pi * w_0**2 / lambda_
        # Generally some more quantities could follow

    def __call__(self, rho, z):
        """
        Arguments:

        *rho*, *z*: Cylindrical coordinates of a spatial point.
        """
        # Shorthand notation
        I_0, w_0 = self.intensity_at_waist_center, self.waist_radius
        z_R = self.rayleigh_range

        w_z = w_0 * sqrt(1.0 + (z / z_R)**2)
        I = I_0 * (w_0 / w_z)**2 * exp(-2.0 * rho**2 / w_z**2)
        return I

为了平衡可读性简洁的符号(公式保持相对较短),您会为物理属性(属性、函数参数等)提出什么一致的命名方案?您能否完善上面的示例?或者也许提出一个更好的方案?

遵循PEP8的指导方针会很好,记住“愚蠢的一致性是小聪明的妖精”。在遵守传统的 80 个字符的行长限制的同时,似乎很难坚持描述性名称。

先感谢您!

4

2 回答 2

4

我想你已经找到了很好的平衡。富有表现力的名称很重要,所以我完全同意使用wavelenght而不是 lambda 作为类属性。这样,界面就保持清晰和富有表现力。

不过,在长公式中,lambda_ 是作为速记符号的不错选择,因为这是光学中普遍接受和广泛使用的波长符号。我认为当你实现一个公式时,你想做的是尽可能接近你写在纸上的方程的形式(或者它们出现在文章中等)。

简而言之:保持界面富有表现力,公式简短。

于 2010-11-19T17:36:43.447 回答
0

使用 Python3,您可以使用实际符号 λ 作为变量名。

我期待编写如下代码:

from math import pi as π

sphere_volume = lambda r : 4/3 * π * r**3
于 2010-11-21T01:59:34.470 回答