@Jon Clementsの答えはかなり良いですが、必要に応じて、クラスにとどまることができますが、すべての定数を静的メソッドに変換します。
class MyConstants(object):
@staticmethod
def constant1():
return 1
次に、それを呼び出すことができます:
some_variable = MyConstants.constant1()
このような処理は保守性の点で優れていると思います---定数を返す以外のことをしたい場合、Jonのソリューションは機能せず、コードをリファクタリングする必要があります。たとえば、constant1
ある時点での定義を変更したい場合があります。
def constant1():
import time
import math
current_time = time.time()
return math.ceil(current_time)
現在の時刻を最も近い秒に戻します。
とにかく、エッセイでごめんなさい:)
したがって、ここでのコメントを考えると、(ファクトリを使用して)自分のやり方で物事を行う場合、静的定数を宣言する場合、クラスでプロパティを使用する場合の実際のオーバーヘッドがわかると思いました。
time_test.py
:
import time
CONSTANT_1 = 1000
CONSTANT_2 = 54
CONSTANT_3 = 42
CONSTANT_4 = 3.14
class Constants(object):
constant_1 = 1000
constant_2 = 54
constant_3 = 42
constant_4 = 3.14
class Factory(object):
@staticmethod
def constant_1():
return 1000
@staticmethod
def constant_2():
return 54
@staticmethod
def constant_3():
return 42
@staticmethod
def constant_4():
return 3.14
if __name__ == '__main__':
loops = 10000000
# static const
start = time.time()
for i in range(loops):
sum = CONSTANT_1
sum += CONSTANT_2
sum += CONSTANT_3
sum += CONSTANT_4
static_const_time = time.time() - start
# as attributes
start = time.time()
for i in range(loops):
sum = Constants.constant_1
sum += Constants.constant_2
sum += Constants.constant_3
sum += Constants.constant_4
attributes_time = time.time() - start
# Factory
start = time.time()
for i in range(loops):
sum = Factory.constant_1()
sum += Factory.constant_2()
sum += Factory.constant_3()
sum += Factory.constant_4()
factory_time = time.time() - start
print static_const_time / loops
print attributes_time / loops
print factory_time / loops
import pdb
pdb.set_trace()
結果:
Bens-MacBook-Pro:~ ben$ python time_test.py
4.64897489548e-07
7.57454514503e-07
1.09821901321e-06
--Return--
> /Users/ben/time_test.py(71)<module>()->None
-> pdb.set_trace()
(Pdb)
これで、効率がわずかに向上しました(1000万ループあたり数秒)。これは、コード内の他の場所にあるものに圧倒される可能性があります。したがって、このようなマイクロ最適化を気にしない限り、3つのソリューションすべてが同様のパフォーマンスを発揮することを確立しました。(その場合は、おそらくCで作業する方がよいでしょう。)3つのソリューションはすべて、読み取り可能で保守可能であり、Pythonを使用するソフトウェア会社のバージョン管理に含まれている可能性があります。したがって、違いは美学にあります。
とにかく、書誌が正しくフォーマットされていなかったので、高校の研究論文で15%のポイントを失ったことがあります。内容は完璧でした、それは私の先生にとってちょうど十分ではありませんでした。ルールを学んだり、問題を解決したりするのに時間を費やすことができることがわかりました。私は問題を解決することを好みます。