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!

Community
  • 1
  • 1

1 Answers1

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358