10

I want to add a method to a single instance of the 'list' class. Example:

a = [1,2]
a.first = lambda self: return self[0]

I know this don't work, but I want something like that works like that. I know its not a good practice, and I know I should do a whole new class, but I think this is possible in Python and haven't figured out how.

I am aware of: Dynamically add member function to an instance of a class in Python and Dynamically binding Python methods to an instance correctly binds the method names, but not the method

but none of those work with a native list.

Thanks!

3
  • 1
    note: don't use return for lambdas. Commented Sep 21, 2011 at 22:29
  • 1
    You want to do a.first = lambda: a[0] or a.first = types.MethodType(lambda self: self[0], a). If you add a function to an object like this Python won't automatically bind it to the object. Commented Sep 22, 2011 at 2:14
  • See stackoverflow.com/questions/6738987/… Commented Jan 7, 2014 at 12:07

1 Answer 1

13

Nothing will work with a native list, since you cannot add methods to a type defined in C. You will need to derive from list and add your method to that class.

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.