python中物理量的命名
我想为我的模拟代码中使用的物理/数学量建立一个良好的命名方案。考虑下面的例子:python中物理量的命名,python,coding-style,naming,readability,scientific-computing,Python,Coding Style,Naming,Readability,Scientific Computing,我想为我的模拟代码中使用的物理/数学量建立一个良好的命名方案。考虑下面的例子: from math import * class GaussianBeamIntensity(object): """ Optical intensity profile of a Gaussian laser beam. """ def __init__(self, intensity_at_waist_center, waist_radius, wavelength):
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
为了在可读性和简明表示法之间取得平衡(公式相对较短),您会为物理属性(属性、函数参数等)提出什么一致的命名方案?你能改进一下上面的例子吗?或者提出一个更好的方案
遵循的指导方针是很好的,记住“愚蠢的一致性是小头脑的妖怪”。在遵守传统的80个字符的行长限制的同时,似乎很难坚持使用描述性名称
提前谢谢你 我想你已经找到了很好的平衡点。表达性名称很重要,所以我完全同意使用wavelenght而不是lambda作为类属性。这样,界面保持清晰和富有表现力 但是,在一个很长的公式中,lambda_u是一个很好的简写符号,因为它是光学中普遍接受和广泛使用的波长符号。我认为,当你实现一个公式时,你要做的是尽可能接近你在一张纸上写下的方程式的形式(或者它们出现在一篇文章中等等)
简而言之:保持界面的表达性,公式的简洁性 使用Python3,您可以使用实际符号λ作为变量名 我期待着编写如下代码:
from math import pi as π
sphere_volume = lambda r : 4/3 * π * r**3
你从80个字符的限制中得到了什么值?这并不是说你要用电子邮件把你的代码发回到20世纪80年代s@Klaus:80个字符的限制很好;e、 例如,可以在屏幕上打开更多的文件,而不必只容纳一个占用大量屏幕空间的很长的队列。(例如,现在在我的两个屏幕上,在xmonad中,我有大约12个窗口是平铺的;大多数窗口的代码裁剪大约为90个字符。)@jimbob我明白你的意思,但我使用IDE。@Klaus:这是另一场辩论的主题。请参阅:cornail:您的代码远远低于80个字符的限制。你在寻找什么?当使用这种速记符号时,几乎每个方法都是从以下内容开始的:)事实上,接口是这样描述的。我不确定的是:函数参数的命名。它们大多是描述性的,但很长(见ctor),并且它们的docstring似乎显示出一定程度的冗余…@cornail-有冗余的函数名和docstring并没有什么错。。。请记住,人们更容易阅读函数名而不是docstring!就我个人而言,我倾向于使用冗长但富于表现力的函数名。