I am new to Python and I am trying to find a way to add new methods to pre-existing classes in Python. For example, to add a .print()
method to the list class.
I know I can create a new class that inherits the list class and add this method like so:
import builtins
class list(list):
def print(self):
builtins.print(self)
But this doesn't modify the pre-existing 'list' class. I can do assignments like this: trial_list = list([3,4,6])
but not like this: trial_list = [3,4,6].
Also, is there a way to view the actual content of the list class besides dir()
and help()
?
The recommended approach to subclass built in container types, is to use the abstract base classes provided in the collections
module:
In the case of list
, you should use collections.UserList
from collections import UserList
class MySpecialList(UserList):
def print(self):
print(self)
seq = MySpecialList([1, 2, 3])
print(seq)
seq.print()
You can now create MySpecialList
objects the way you do with a plain python list
.
Subclassing requirements: Subclasses of UserList are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source.
Of course you can override the methods of list
to provide your MySpecialList
with the behavior you need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.