Python中物理量的命名

3 投票
2 回答
717 浏览
提问于 2025-04-16 07:21

我想为我模拟代码中使用的物理和数学量建立一个好的命名规则。考虑以下例子:

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个字符行长度限制的同时,似乎很难保持描述性的名称。

提前谢谢你!

2 个回答

0

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

我期待着能写出这样的代码:

from math import pi as π

sphere_volume = lambda r : 4/3 * π * r**3
4

我觉得你已经找到了一个不错的平衡点。用有表现力的名字很重要,所以我完全同意把 wavelenght 用作类属性,而不是用 lambda。这样一来,接口就保持了清晰和表达性。

不过,在一个长公式中,lambda_ 是个不错的选择,因为它是光学中常用的简写,大家都能理解。当你实现一个公式时,最好尽量和你在纸上写的方程式保持一致(或者和文章中出现的样子一样)。

简单来说:保持接口的表达性,公式要简短。

撰写回答