1

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 発生の重複を組み合わせることができるようですか?

4

2 に答える 2

2

可変タプルが必要な場合は、リストを使用してください。

編集:

これを試して

class FrankenList(object):
    def __init__(self, init=None):
        self.__data = init or []

    def __getitem__(self, key):
        return self.__data[key]

    def __repr__(self):
        return repr(self.__data)

    def __str__(self):
        return str(self.__data)
于 2010-11-29T18:01:00.177 に答える
1

非常に簡単です。リストをラップするだけです。

class ImmutableList(object):
    def __init__(self, *args):
        self.__values = args; # internally we store the values in a list

    # make imuList[0] = 2 raise an error, just like a tuple would
    def __setitem__(self, index, value):
        raise TypeError('ImmutableList does not support item assignment')

    # del imuList[0] should also raise
    def __delitem__(self, index, value):
        raise TypeError('ImmutableList does not support item deletion')**

    # make our imuList indexable, also catch the normal index error and raise one
    # that tells that this is an immutable list, will make it easier to debug :)
    def __getitem__(self, index):
        try:
            return self.__values[index]

        except IndexError:
            raise IndexError('ImmutableList index out of range')

    # the usual stuff
    def __repr__(self):
        return repr(self.__values)

    def __str__(self):
        return str(self.__values)

# create a new imulist
e = ImmutableList(1, 2, 3, 4)

# works!
print e[0]

# raises an error
e[0] = 5

# raises another error
print e[9]

self._valuesあとは、クラス内で変更するだけです。最後のアドバイスとして、 Python はprivate membersself._valuesをサポートしていないため、外部からいじることはまだ可能です。

リストから直接サブクラス化することにより、 の操作に対してさらに対策を講じることができますが__values、それはより多くの作業であり、使用するなどして値をいじることができますlist.__setitem__(imListInstance, 0, 5)

于 2010-11-29T18:32:54.030 に答える