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!
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.
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.
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.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With