Supplementary and packaging reflection of several built-in functions of standard type

First, we learned __getattr__ __setattr__ and usage __delattr__ in the previous chapters,

In fact, these are the kind of built-in functions, if we rewrite these functions in a class of their own definition, the

Will directly cover the default class features several functions, from another angle, we can directly rewrite these functions, it has been in

Add new features functional basis

class Foo: 
    X = 2 
    DEF the __init __ (Self, Y): 
        self.y = Y 

    DEF __delattr __ (Self, Item): 
        Print ( "executing __setattr__, this can add a new function oh") 
        Self .__ dict __ POP (Item. ) 

F1 = Foo (. 7) 
Print (F1 .__ dict__ magic) 
del f1.y 
Print (F1 .__ dict__ magic)

 

Second, a standard type of packaging

so are the class list str tuple

We can create a new class that inherits them, while adding new features

class List(list):

    def show_midle(self):  #求列表中间值
        mid_index = int(len(self)/2)
        return self[mid_index]

l2 = List('hellojinling')
print(l2.show_midle())
print(l2)

  

List class (List): 

    DEF append (Self, p_object): # append method to modify 
        print ( "Adding") 
        IF of the type (p_object) IS str: # determine what, just add strings 
            Super () append (p_object). 

    DEF show_midle (self): # find a listing intermediate value 
        mid_index = int (len (Self) / 2) 
        return Self [mid_index] 

L2 = list ( 'hellojinling') 
Print (L2) 
l2.append ( "LOVE") 
Print (L2)

  

 

 

Guess you like

Origin www.cnblogs.com/dabai123/p/11605584.html