python中物理量的命名

2024-01-01

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

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

您会为物理属性(属性、函数参数等)提出什么一致的命名方案,以便在可读性 and 简洁的符号(公式仍然相对较短)?您能改进一下上面的例子吗?或者提出更好的方案?

最好遵循以下指导方针PEP8 http://www.python.org/dev/peps/pep-0008/,记住“愚蠢的一致性是小头脑的恶魔”。在遵循传统的 80 个字符的行长度限制的同时,坚持使用描述性名称似乎很困难。

先感谢您!


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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python中物理量的命名 的相关文章

随机推荐