current position:Home>Getting started with Python - object oriented - special methods

Getting started with Python - object oriented - special methods

2021-08-22 03:53:42 zwx901323

 

 

 

 

 

Call interception function

 

class Message:
    def send(self,info):
        print(" message sending :",info)
class Me:
    def __getattribute__(self, item):
        print("attribute:", item)     # Perform the intercepting operation 
        return object.__getattribute__(self, item) #  Release the intercepting operation 
    def send(self,info):
        print(" message sending :",info)

class Lanjie:
    def __getattribute__(self, item):
        if item == "content":
            return " This is intercepting information "
        elif item == "send":
            return self.other  #  Returns a reference to another method 
        else:
            return object.__getattribute__(self, item)  #  Let go of interception 
    def send(self,info):
        print(" message sending :",info)
    def other(self, note):
        print("【 Alternative method 】other:", note)

if __name__ == '__main__':
    m = Message()
    print("============= Don't intercept code demonstrations :=============")
    m.info=" use Baidu Search "
    print(m.info)
    m.send("www.baidu.com")
    print("============ Intercept code demo :=============")
    me = Me()
    me.info = "www.google.com"
    print(me.info)   # Call interception 
    me.send("www.google.com")# Call interception 

    # All interceptions , It's all done automatically 
    print("============ Demonstration of replacement method after interception :=============")
    lj = Lanjie()
    lj.content = "lanjie Of content"
    print(lj.send("www.com"))

Get attribute dictionary

class Message(object):
    def __init__(self, note):
        self.__note = note
class Me:
    def __init__(self, note):
        self.__note = note  #  Define private properties 
    def remove_note(self): #note Encapsulate for attributes , It can only be accessed through the interior of the class 
        del self.__note
    def get_note(self):
        return self.__note

    def __setattr__(self, key, value):
        print("【setattr】key={},value={}".format(key, value))
    def __getattr__(self, item):
        print("【getattr】item=", item)
    def __delattr__(self, item):
        print("【del attr】item =", item)

class M:
    def __init__(self, note):
        self.__note = note  #  Define private properties 
    def remove_note(self): #note Encapsulate for attributes , It can only be accessed through the interior of the class 
        del self.__note
    def get_note(self):
        return self.__note

    def __setattr__(self, key, value):
        print("【setattr】key={},value={}".format(key, value))
        self.__dict__[key] =  value
    def __getattr__(self, item):
        print("【getattr】item=", item)
        return "{} Property does not exist , no return value ".format(item)
    def __delattr__(self, item):
        print("【del attr】item =", item)
        self.__dict__.pop(item)   #  Delete attributes from the dictionary 
if __name__ == '__main__':
    m = Message("note attribute ")
    m.content = "www.baidu.com"
    print(m.__dict__)
    #  In the program msg Two properties of the instantiated object , Is stored in a dict In the dictionary 
    #  Set the properties : Must be set manually dict Parameter data 
    #  Get properties : Only when the attribute does not exist will it be intercepted 
    #  Delete attribute block :
    #       "setattr, getattr, delattr")
    print("======== Start attribute listening =========")
    me = Me("www.google.com")
    print(" Get existing properties :", me.get_note())
    print(" Get properties that don't exist :", me.content)
    me.remove_note()
    print("======== Property listener =========")
    m = M("www.google.com")
    print(" Get existing properties :", m.get_note())
    print(" Get properties that don't exist :", m.content)
    m.remove_note()

Get subclass instantiation information

#  Subclass gets the instantiation of the parent class , You can define the metadata of the parent class 

class Parent:
    def __init__(self):
        print("parent The initialization init")
    def __init_subclass__(cls, **kwargs):
        print(" Parent class parent_subclass:", cls)
        print(" Parent class parent_subclass:", kwargs)

class Sub(Parent, url="www.baidu.com", title=" Baidu "):
    def __init__(self):
        print(" Subclass sub Of init")

if __name__ == '__main__':
    sub = Sub()

"""
 Parent class parent_subclass: <class '__main__.Sub'>
 Parent class parent_subclass: {'url': 'www.baidu.com', 'title': ' Baidu '}
 Subclass sub Of init
"""

Custom iteration

class Message:
    def __init__(self, max):
        self.__max = max
        self.__foot = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.__foot >= self.__max:
            raise StopIteration()  # If the loop , Stop iterating 
        else:
            val = self.__max - self.__foot
            self.__foot += 1
            return val
if __name__ == '__main__':
    m = Message(10)
    for i in m:
        if i ==1:
            break   #  no need break end , It's a dead cycle 
        print(i, end=",")
# Execution results :10,9,8,7,6,5,4,3,2,

Select Invert

class Message:
    def __init__(self):
        self.__mlist = [" Baidu ", " Ali ", " tencent "]
    def get_list(self):
        return self.__mlist
    def __reversed__(self):
        self.__mlist = reversed(self.__mlist)

if __name__ == '__main__':
    m = Message()
    print(" The following is a custom inversion operation :")
    reversed(m)

    for i in m.get_list():
        print(i, end=",")
"""
 The following is a custom inversion operation :
 tencent , Ali , Baidu ,
"""

Dictionary operation support

# The dictionary is obtained as key,value, And dictionaries 【】
 #  Consistent with the operation of the dictionary 


class Message:
    def __init__(self):
        self.__map = {}
    def __setitem__(self, key, value):
        print("【set item】 Set up the data :key={}, value={}".format(key, value))
        self.__map[key] = value
    def __getitem__(self, item):
        print("【get item】 get data :item=", item)
        return self.__map[item]
    def __len__(self):
        return len(self.__map)
    def __delitem__(self, key):
        print("【del item】 Delete data now :item=", key)
        self.__map.pop(key)
if __name__ == '__main__':
    m = Message()
    print("===== Set up the data ======")
    m[" Baidu "] = "www.baidu.com"
    print("===== Search for ======")
    print(m[" Baidu "])
    print("===== Get the number ======")
    print(" Get the number of elements :", len(m))
    print("===== Delete ======")
    del m[" Baidu "]
"""
===== Set up the data ======
【set item】 Set up the data :key= Baidu , value=www.baidu.com
===== Search for ======
【get item】 get data :item=  Baidu 
www.baidu.com
===== Get the number ======
 Get the number of elements : 1
===== Delete ======
【del item】 Delete data now :item=  Baidu 
"""

 

copyright notice
author[zwx901323],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2021/08/20210822035338833o.html

Random recommended