current position:Home>How to implement a custom list or dictionary in Python

How to implement a custom list or dictionary in Python

2022-01-30 11:15:56 Know the small at first sight

Antecedents feed

In a lot of python In the library , We can see that sometimes , Library authors will use some very special “ list ” perhaps “ Dictionaries ”. Although they look like a list or dictionary , But the method used is different , That's because it's not true python The original list and dictionary in , It was created by the author himself . that , How can we create our own lists and dictionaries ?

Magic methods

Use two underscores before and after , It is generally called magic method , Like the ones that we see all the time __init__, It's a magic method . Generally speaking , When we define the variable name ourselves , Don't define variable names that look like magic methods . After the magic method is defined , Can be called automatically when appropriate , Generally, it does not need to be called manually .

stay python in , Implement a sequence , We need the following four magic methods

__len__(self): This method should return the number of elements , For example, we often use len(), It is through this magical method .

__getitem__(self, key): This method gets a key, We should return a value.

__setitem__(self, key, value): This method defines a key And a value, Used to define key value pairs .

__delitem__(self, key): This method defines the use of del When , What will be done 
 Copy code 

in addition , Generally speaking , The wrong key should raise TypeError abnormal , The wrong index should cause IndexError abnormal

Usage method

stay python List of , Only numbers can be used as indexes , If you use numbers in strings , Then an exception will be thrown . therefore , We can try , Expand the original list , So that it can accept strings as the index of the list .

class XiaList: """  author : Blind brother   Time :2021-10-26  explain : A pseudo list , Can accept both string index and numeric index   Contact information :qq1413274264 """ def __init__(self, old_list): self.num = len(old_list)
        self.list = old_list
    def __len__(self):
        return self.num
    def __getitem__(self, key):
            k = int(key)
            return self.list[k]
            raise TypeError
    def __setitem__(self, key, value):
            k = int(key)
            self.old_list[key] = value
            raise TypeError
if __name__ == "__main__":
    x = XiaList([1, 2, 3, 4, 5])
 Copy code 

Be careful , Such a self built list , There are many problems , Almost all the methods about lists can no longer be used .

To use by inheritance

In order to solve the normal list, the method can no longer be used , We can consider direct inheritance list, All the ways to get a normal list .

class XiaList2(list): """  author : Blind brother   Time :2021-10-26  Contact information :qq1413274264  explain : Use XiaList2 To get the element , If the element is an integer , It shows how many million  """ def __init__(self, *args): super().__init__(*args) def __getitem__(self, key): if not isinstance(key, int): raise TypeError try: n = int(super().__getitem__(key))
            return str(n / 10000) + " ten thousand "
            return super().__getitem__(key)
if __name__ == "__main__":
    x = XiaList2([10000, 52000, 99999, "314125926", "abcd"])
    for i in range(len(x)):
 Copy code 

copyright notice
author[Know the small at first sight],Please bring the original link to reprint, thank you.

Random recommended