Python の可変オブジェクトと不変オブジェクトの概念を理解しています。問題ありません。不変オブジェクトの固有値を直接変更することはできませんが、不変オブジェクトのインスタンスは別の値で再インスタンス化できます。私がやりたいのは、制御された方法で独自の値を再割り当てできるタプルのサブクラスに内部関数を構築することです。これは、私が見つけられないように見える基本的な機能である可能性があり、助けていただければ幸いです。
たとえば、これが私ができるようにしたいことですが、これは明らかに機能しません。
class myTuple(tuple):
def __new__(self):
initialValue = [1, 2, 3]
return super(myTuple, self).__new__(self, initialValue)
def resetMyself(self):
newValue = [4, 5, 6]
self = tuple(newValue)
以下の結果で...
>>> foo = myTuple()
>>> print foo
(1, 2, 3)
>>> foo.resetMyself()
>>> print foo
(4, 5, 6)
このサイトでこのような質問に対する多数の回答を読んだことから、「なぜこれをやりたいのですか?」と答える傾向がある人もいると思います。しかし、実際にそうである場合は、おそらく「絶対にできない、どうやってもできない」など、より直接的な回答で応答スペースを節約しましょう。
どうもありがとうございました!
編集、以下の回答をありがとう、これが私が最終的に得たものです...
class semiImmutableList(list):
def __setitem__(self, *args):
raise TypeError("'semiImmutableList' object doesn't support item assignment")
__setslice__ = __setitem__
def __delitem__(self, *args):
raise TypeError("'semiImmutableList' object doesn't support item deletion")
__delslice__ = __delitem__
def append(self, *args):
raise AttributeError("'semiImmutableList' object has no attribute 'append'")
def extend(self, *args):
raise AttributeError("'semiImmutableList' object has no attribute 'extend'")
def insert(self, *args):
raise AttributeError("'semiImmutableList' object has no attribute 'insert'")
def remove(self, *args):
raise AttributeError("'semiImmutableList' object has no attribute 'remove'")
def pop(self, *args):
raise AttributeError("'semiImmutableList' object has no attribute 'pop'")
def __init__(self):
x = [1, 2, 3]
super(semiImmutableList, self).__init__(x)
def resetMyself(self):
super(semiImmutableList,self).append(5)
あなたが見ることができる上記の改善/調整は投稿してください. AttributeError 発生の重複を組み合わせることができるようですか?