问题描述
我有一个Python模块,其中包含许多类,每个类都代表一种具有其属性(例如密度,比热)的特定物理材料。有些属性只是该类的 float
成员,但许多属性取决于某些参数,例如温度。我通过 @staticmethod
s实现了这一点,即所有类都看起来像
I have a Python module that contains a number of classes, each representing a particular physical material with its properties (e.g., density, specific heat). Some of the properties are just float
members of the class, but many depend on some parameter, e.g., the temperature. I implemented this through @staticmethod
s, i.e., all of the classes look like
class Copper(object):
magnetic_permeability = 1.0
@staticmethod
def density(T):
return 1.0 / (-3.033e-9 + 68.85e-12*T - 6.72e-15*T**2 + 8.56e-18*T**3)
@staticmethod
def electric_conductivity(T, p):
return 1.0141 * T**2 * p
@staticmethod
def specific heat(T):
return ...
class Silver(object):
...
class Argon(object):
...
...
Class
es因此仅充当所有容器的容器数据以及大量的 @staticmethod
s让我怀疑对于这种用例可能存在更合适的设计模式。
The Class
es thus merely act as containers for all the data, and the abundance of @staticmethod
s has me suspecting that there may be a more appropriate design pattern for this use case.
有任何提示吗?
推荐答案
您可以将模块命名为 copper
并全部创建这些作为模块级功能,然后导入铜; Copper.density(0)
。
You could name your module copper
and create all of these as module level functions, then import copper; copper.density(0)
.
但是,如果有人从铜进口密度中得出怎么办
,还有一个名为钴
的模块,另一个名为碳
的模块,另一个名为氯的模块
等,都具有自己的密度
函数?嗯。
But what if someone does from copper import density
, and you also have a module called cobalt
and another called carbon
and another called chlorine
etc., all with their own density
functions? Uh oh.
因为,您可以对此进行记录,并希望您的用户足够了解以仅导入该模块。或者您可以采取您的方法;在这种情况下,我考虑将所有元素放在一个名为 elements
的模块中,然后用户可以从元素中导入Copper
。则使用静态方法将是适当的。
Since we're all consenting adults here, you can document this and expect your users to know well enough to import just the module. Or you can take your approach; in this case, I would consider putting all of your elements in one module called elements
, then the user can from elements import Copper
. Static methods would then be appropriate.
这篇关于仅具有静态方法的类的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!