こんにちは、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 行目のエラーの意味がわかりません。誰でも説明できますか?例を修正することもいいでしょう。前もって感謝します。