A container portion Python magic function (__del __, __ len __, __ getitem __, __ setitem __, __ delitem__)

In order to deepen the impression, but also for the future to better memories, or record it.

Sequence (similar to the sets, lists, strings), mapping (dictionary-like) substantially set of elements, to achieve their basic behavior (protocol), immutable objects requires two protocols, the protocol requires four variable object.

__len __ (self): returns the number of elements (immutable one subject in need protocol)

__getitem __ (self, key) or __getitem __ (self, index), returns the execution value (one protocol required immutable object) associated with the input

__setitem __ (self, key, values) or __setitem __ (self, index, values), setting values ​​corresponding to the value of the specified input

__delitem__ (self, key) Deletes the specified key value

 

__del__, when executed destructor instance of the class object does not exist.

 

I wrote a custom similar to the following list of classes, instances of the class after the default parameter None in front of 10, and can not delete the previous five empty None. (Casually said, and began to write)

DEF check_index (index): 
    IF index <. 5: 
        The raise IndexError ( 'index MUST Greater Within last 10') 


class S_List: 
    DEF the __init __ (Self): 
        self.ll = [None] * 10 

    DEF __len __ (Self): # extraction parameter length 
        len return (self.ll) 

    DEF the __getitem __ (Self, index): # remove parameters 
        return self.ll [index] 

    DEF __setitem __ (Self, index, value): # set parameters 
        check_index (index) 
        self.ll [index] = value 

    __delitem __ DEF (Self, index): 
        check_index (index) 
        self.ll.pop (index) 

    DEF __str __ (Self): # when print objects, the output list itself 
        return str (self.ll) 

    DEF __del __ (Self): no manual # delete released at the end of the program 
        Print ( 'I was released!' ) 


SL = S_List ()
del SL [. 3] 

Print (the isinstance (SL, S_List)) 
Print (F 'outputs the original data: {SL}') 
SL [. 6] = 'Six' 
Print (F 'modified original data: {SL}') 
Print (f 'takes a random value: SL {[. 1]}') 
del SL [. 6] 
Print (f 'after the second modification of the original data: {} SL') 
del SL [. 3] 
# SL [. 4] = ' OH ' 
Print (SL)

 

 Normal output:

True 
output raw data: [None, None, None, None, None, None, None, None, None, None] 
modified original data: [None, None, None, None, None, None, 'six', None, none, none] 
easily take a value: none 
after the second modification of the original data: [none, none, none, none, none, none, none, none, none] 
[none, none, none, none, none, none, none, none, none] 
I was released!

 Error prompt:

Traceback (most recent call last):
  File "/Users/shijianzhong/Desktop/yunzuan_buy/study_base.py", line 81, in <module>
    del sl[3]
  File "/Users/shijianzhong/Desktop/yunzuan_buy/study_base.py", line 73, in __delitem__
    check_index(index)
  File "/Users/shijianzhong/Desktop/yunzuan_buy/study_base.py", line 53, in check_index
    raise IndexError('index must greater than 10')
IndexError: index must greater than 10
我被释放了!

 

This is from a basic no pseudo-dictionary definition of what method, the elements can not be increased, and the index, count and other methods can not be used because there is no written.

Good list mode can be inherited or dict class, modify the conditions required limit on the inside, in this case, out of the instance of all of the original objects can inherit methods.

 

This time I can really define a super positive list, according to my needs. This list is now required to initialize None has five elements, in front of five elements can not be modified, added behind the element must be str

DEF check_str (the params): 
    IF Not the isinstance (the params, STR): 
        The raise a ValueError ( 'Parameters MUST IS String') 
    
DEF check_index (index): 
    IF index <. 5: 
        The raise IndexError ( 'index MUST Greater Within last 10') 

class Super_List ( List): 
    DEF the __init __ (Self): 
        Super (Super_List, Self) .__ the init __ () # call the parent class initialization 
        self + = [None] * 5 # of initialization parameters modified 

    def append (self, * args) : # of append restriction parameters 
        for in args I: 
            check_str (I) 
        return Super (Super_List, Self) .append (* args) 
 
    DEF insert (Self, index, * args): # insert parameter (index and insert elements) to be limiting
        check_index (index) # determines the insertion position 
        for in args I: 
            check_str (I) 
        return Super (Super_List, Self) .insert (index, * args) 

    DEF Extend (Self, * args): # expansion element list judgment 
        TEMP = args [0] 
        for I in TEMP : 
            check_str (I) 
        Super (Super_List, Self) .extend (* args) 
    
    DEF __delitem __ (Self, index): # index del command judged 
        check_index (index) 
        Super (Super_List, Self) .__ delItem __ (index) 

    DEF Clear (self): # clear command prohibited 
        The raise TypeError ( 'No permission') 

ss_l = Super_List () 
Print (ss_l) 
ss_l.append ( '. 1') 
ss_l.insert (. 5, 'A') 
ss_l.extend ([ ' a ',' b ',' c ']) 
ss_l.clear () 
Print (ss_l)

 Wrote nearly half an hour, I feel a lot of lists and increase the delete command, the command does not override all have some, but the logic is the same.

 

If executed automatically when certain commands to access parameters in someone, you can write __getitem__ below.

 

 

 

Wrote nearly half an hour, I feel a lot of lists and increase the delete command, the command does not override all have some, but the logic is the same.
[Xiele xiǎoshi Ge Kuai table, gǎnjue liebiǎo de zengjia yǔ shanchu henduo mingling, mingling meiyǒu suǒyǒu yixie yǒu fast Xie, staging luoji Haishi Yiyang de.]
Wrote nearly half an hour, I feel a lot of lists and increase the delete command, the command does not override all have some, but the logic is the same.

Guess you like

Origin www.cnblogs.com/sidianok/p/11790087.html