1

こんにちは、Python での定数の作成(リンクからの最初の回答) から見つかったこの例を使用して、Python で const を作成し、インスタンスをモジュールとして使用しようとしています。

最初のファイル const.py には

# Put in const.py...:
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__ in (name):
            raise self.ConstError("Can't rebind const(%s)"%name)
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()

そして残りは、たとえば test.py に行きます。

# that's all -- now any client-code can
import const
# and bind an attribute ONCE:
const.magic = 23
# but NOT re-bind it:
const.magic = 88      # raises const.ConstError
# you may also want to add the obvious __delattr__

私は2つの変更を加えましたが、Python 3を使用しているため、まだエラーが発生します

Traceback (most recent call last):
  File "E:\Const_in_python\test.py", line 4, in <module>
    const.magic = 23
  File "E:\Const_in_python\const.py", line 5, in __setattr__
    if self.__dict__ in (name):
TypeError: 'in <string>' requires string as left operand, not dict

5 行目のエラーの意味がわかりません。誰でも説明できますか?例を修正することもいいでしょう。前もって感謝します。

4

3 に答える 3

4

これは奇妙に見えます(どこから来たのですか?)

if self.__dict__ in (name):

あるべきではない

if name in self.__dict__:

それはあなたの例を修正します

Python 3.2.3 (default, May  3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import const
>>> const.magic = 23
>>> const.magic = 88
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "const.py", line 6, in __setattr__
    raise self.ConstError("Can't rebind const(%s)"%name)
const.ConstError: Can't rebind const(magic)

このconstハックが本当に必要ですか?多くのPythonコードはそれなしでどういうわけか動作するようです

于 2012-10-03T10:04:57.203 に答える
3

この行:

   if self.__dict__ in (name):

する必要があります

   if name in self.__dict__:

... dictが属性名にあるかどうかではなく、属性がdictにあるかどうかを知りたい(文字列には辞書ではなく文字列が含まれているため、これは機能しません)。

于 2012-10-03T10:04:23.690 に答える
0

多分kkconst - pypiが検索対象です。

str、int、float、datetime をサポートし、const フィールド インスタンスはその基本型の動作を維持します。orm モデルの定義と同様に、BaseConst は const フィールドを管理する Constant Helper です。

例えば:

from __future__ import print_function
from kkconst import (
    BaseConst,
    ConstFloatField,
)

class MathConst(BaseConst):
    PI = ConstFloatField(3.1415926, verbose_name=u"Pi")
    E = ConstFloatField(2.7182818284, verbose_name=u"mathematical constant")  # Euler's number"
    GOLDEN_RATIO = ConstFloatField(0.6180339887, verbose_name=u"Golden Ratio")

magic_num = MathConst.GOLDEN_RATIO
assert isinstance(magic_num, ConstFloatField)
assert isinstance(magic_num, float)

print(magic_num)  # 0.6180339887
print(magic_num.verbose_name)  # Golden Ratio
# MathConst.GOLDEN_RATIO = 1024  # raise Error, because  assignment allow only once

詳細な使用方法は、pypi URL を読むことができます: pypiまたはgithub

同じ答え: Python で定数を作成する

于 2015-12-26T11:10:51.047 に答える