Python method to request attribute component that formed by list
<p>I need to access an item from an attribute that formed in list. This is my code:</p>

<pre><code>class Foo:

    def __init__(self):
        self.__words = []

    @property
    def word(self, index):
        return self.__words[index]

    @word.setter
    def word(self, word):
        self.__words.append(str(word))
</code></pre>

<p>When I tested it in terminal, its result is as follow:</p>

<pre><code>import coba
a = coba.Foo()
a.word = 'ok'
a.word(0)
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: word() missing 1 required positional argument: 'index'
</code></pre>

<p>Why I cannot access list item using that method? Thank you for helping.</p>

<p>I believe you cannot add arbitrary arguments to a method decorated by <code>@property</code>. So, if you really want to do this, you can return a method that takes an index instead of trying to get the value itself:</p>

<pre><code>class Foo:
    def __init__(self):
        self.__words = []

    @property
    def word(self):
        return lambda index: self.__words[index]

    @word.setter
    def word(self, word):
        self.__words.append(str(word))
        print(self.__words)

a = Foo()
a.word = 'ok'
print(a.word(0))  # 'ok'
</code></pre>

<p>Note that this is generally not a very Pythonic class. Python takes a "trust the caller" approach, so it's rare to see read-only or restricted write implementations like this. As others have said, it's much more common to just use the internal list and trust the caller to not mess with it in unintended ways.</p>

python list python-3.x