Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a method to a list instance in python

Tags:

python

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!

like image 547
Camilo Andrés Jiménez Cruz Avatar asked Sep 21 '11 22:09

Camilo Andrés Jiménez Cruz


People also ask

What is __ add __ in Python?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1. __add__(obj2). For example, let's call + on two int objects: n1 = 10.

How do I add a method to an existing class in Python?

The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations. The method can also be defined outside the scope of the class.

What is __ new __ in Python?

The __new__() is a static method of the object class. When you create a new object by calling the class, Python calls the __new__() method to create the object first and then calls the __init__() method to initialize the object's attributes.

How do I add an instance in Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.


1 Answers

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.

like image 78
Ignacio Vazquez-Abrams Avatar answered Oct 06 '22 01:10

Ignacio Vazquez-Abrams