0

In python how do you add an attribute to a list to perform an operation?

Suppose you have a class like:

class TestClass:

    def __init__(self, lst):
        self.lst = lst

    def test(self, lst):
        """

        >>> t1 = TestClass([1,2,3,4])
        >>> t1.test(self.lst).size
        4

        """

if you attach the attribute size to the function test it will return the length of self.lst. So, return len(self.lst)

4
  • That wouldn't make sense - and why would you want to do that over return len(self.lst) - and what's that other lst in test? What exactly are you trying to do - I suspect it isn't making function attributes... Commented Jan 29, 2014 at 0:49
  • just as an example. Wasn't going to use that for what i'm doing. But just for this example. Commented Jan 29, 2014 at 0:50
  • 3
    Would you care to explain what it is you are doing then? - I strongly suspect this is an XY problem, and any answers to what you might be asking may not be suitable for what you're actually trying to achieve here... Commented Jan 29, 2014 at 0:51
  • To be more correct, you're talking about methods here rather than functions. Commented Jan 29, 2014 at 0:51

1 Answer 1

2

The issue is that:

t1.test(self.lst).size

Is equivalent to:

a = t1.test(self.lst)
a.size

You're not accessing an attribute on the method, but on the return value of the method. You may want something like this:

class TestClass:
    def __init__(self, lst):
        self.lst = lst

    def test(self):
        # do something to self.lst (rather than passing it in again)

    @property
    def size(self):
        return len(self.lst)

>>> t = TestClass([1,2,3,4])
>>> t.test()
...
>>> t.size
4

If you really want to add this to the list, then you'll need to wrap it in something that provides the size method:

class SizeList(list):
    @property
    def size(self):
        return len(self)

class TestClass:
    def __init__(self, lst):
        self.lst = SizeList(lst)

    def test(self):
        # do something here
        return self.lst

>>> t = TestClass([1,2,3,4])
>>> t.test().size
4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.