我希望为我的仿真代码中使用的物理/数学量建立一个良好的命名方案。考虑以下示例:
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个字符行长度限制时,似乎难以坚持使用描述性名称。
提前致谢!
foo**0.5
而不是sqrt(foo)
,以及/ e**(2 * bar)
而不是* exp(-2 * bar)
。 - Beni Cherniavsky-Paskin