python foundation 13 item/__ str__ Method/__ format__ Method/__ slots__ Method/_ cal_ method

Posted by Maverickb7 on Wed, 19 Jan 2022 08:39:26 +0100

  • Files are also objects, and you can also use the four methods in the reflection module
  • In team collaboration, the pluggable mechanism uses reflection to judge whether there is a corresponding function in the next module
  • Import is to take the file and execute it in the current file
  • #In this way, the module itself is imported, and then the reflection method is applied
    import
    sys obj1=sys.modules[__name__] print('==>',hasattr(obj1,'x')) 
  • Built in function supplement

  • isinstance(obj,cls) determines whether an object obj is an instance generated by a class itself or a subclass
  • issubclass(sub,super) determines whether sub is a subclass of super
  • type (b1) displays the class to which instance b1 belongs
  • ! It's no use__ getattribute__: Property exists, return a matching value. Property does not exist, an exception is thrown
  • class Foo:
        def __init__(self,x):
            self.x=x
    
        def __getattr__(self, item):
            print('The implementation is getattr')
    
        def __getattribute__(self, item):#This will be triggered regardless of whether the attribute can be found,
            print('The implementation is getattribute')
            raise AttributeError('An exception was thrown')#Only when this instruction is thrown will it be triggered getattr
    
    f1=Foo(10)
    # f1.x
    f1.xxxxx

     

  • item series

  • #The calling method of. Is related to getattr and other three methods, and the dictionary operation is related to getitem and other three methods
    class
    Foo: def __getitem__(self, item): print('getitem') return self.__dict__[item] def __setitem__(self, key, value): print('setitem') self.__dict__[key] = value # Method of adding key value pairs to analog dictionary def __delitem__(self, key): print('delitem') self.__dict__.pop(key) f1 = Foo() print(f1.__dict__) # f1.name='egon'#setitem will not be triggered in this way f1['name'] = 'egon' # Assignment in dictionary mode will trigger setitem method f1['age'] = 18 print(f1.__dict__) del f1.name # adopt.The way, with delattr That way, match, don't match delitem The way print(f1.__dict__)
  • Change the string display of the object

  • Everything is an object. When printing, it should be an object in essence. The print result of some objects is not an object. It indicates that you can customize some methods in your own class to control the form of object output from the class instance
  • class Foo:
        #Class has a default str Method. If it is not customized, the system's
        def __str__(self):#Customize the print results of the objects of this class instance
            return 'Display of self customized objects'
    f1=Foo()
    print(f1)#The essence is called--str(f1)--The way is f1.__str__()method

     

  • class Foo:
        #Class has a default str Method. If it is not customized, the system's
        
        def __str__(self):
            return 'This is str'
        def __repr__(self):#Customize the print results of the objects of this class instance
            return 'The name is%s Age is%s'%(self.name,self.age)
    #Cannot return non string format f1
    =Foo() #Enter in the interpreter f1#The essence is to call the -- repr(f1) -- method, which is F1__ repr__ () method print(f1)#If so str Just find str,If not, find repr. If none, find the built-in system

     

  • Customize the format for the instance

  • format_dic = {
        'ymd': '{0.year}{0.mon}{0.day}',
        'm-d-y': '{0.mon}-{0.day}-{0.year}',
        'y:m:d': '{0.year}:{0.mon}:{0.day}'
    }
    
    
    class Date:
        def __init__(self, year, mon, day):
            self.year = year
            self.mon = mon
            self.day = day
    
        def __format__(self, format_spec):
            print('I did')
            print('-->', format_spec)
            if not format_spec or format_spec not in format_dic:
                format_spec = 'ymd'
            fm = format_dic[format_spec]
            return fm.format(self)
    
    
    d1 = Date(2016, 12, 26)
    # format(d1)
    print(format(d1, 'y:m:d')) 
  • slots property

  • _ solts_ Is a class variable. The variable value can be a list, tuple, iteratable object, or string (meaning that all instances have only one data attribute)
  • The dictionary of the class is shared and can be called by the instance generated by the class
  • When there are few attributes of a class, but thousands of instances need to be generated, each instance has independent storage space, which is a waste of memory
  • _ slots_ After playing, each instance no longer has_ dict_, In this way, there is no need to create an attribute dictionary for each instance, saving memory space
  • class Foo:
        # __slots__ = ['name','age']
        __slots__ = 'name'  # Instead of creating an attribute dictionary for each instance, you can find it in the class attribute dictionary
        # Disadvantages: only one can be created per instance name Cannot create other properties
        # The advantage is to save memory, rather than limiting instance extension properties
    
    
    f1 = Foo()
    f1.name = 'egon'
    print(f1.name)
    
    # print(f1.__dict__)
    print(f1.__slots__)

     

  • _ doc_ Class method

  • class Foo:
        'I'm describing information'  # This information cannot be inherited
        pass
    class Bar(Foo):
        pass
    print(Bar.__doc__)
  • c1.__module__ Gets which module the current C1 is generated by
  • c1.__class__ Check which class of which module C1 is generated
  • Destructor__ del__ Function, which automatically triggers execution when an object is released in memory. Generally, it does not need to be defined. Only run after the instance is deleted or the program is executed
  • __ call__, Parentheses are added after the object to trigger execution and the call does not move. f1(), that is, instance f1 calls the call method of the class that created the instance
    class Foo:
        def __call__(self, *args, **kwargs):
            print('The instance is executed, obj()')
    
    
    f1 = Foo()
    f1()  # Execution is the execution of the class that calls the instance call method
    Foo()  # Call to create the Foo Class of instance call method#Class is an object, so it is also generated by other classes

 

  • Iterator protocol

  • for loop steps, first through_ iter_ Method to make the object iteratable
  • #Manually implement the iterator protocol, including iter and next methods
    class Foo: def __init__(self, n): self.n = n def __iter__(self): return self def __next__(self): if self.n==100: raise StopIteration('Terminated') self.n += 1 return self.n f1 = Foo(10) print(f1.__next__()) print(f1.__next__()) print(f1.__next__()) print(next(f1)) for i in f1: print(i)

     

  • # The iterator implements the Fibonacci sequence
    class Fib:
        def __init__(self):
            self._a = 1
            self._b = 1
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self._b > 100:
                raise StopIteration('Terminated')
            self._a, self._b = self._b, self._a + self._b
            return self._a
    
    
    f1 = Fib()
    print(next(f1))
    print(next(f1))
    print(next(f1))
    print('>>>>>>>>>>>>>>')
    for i in f1:#Then the for loop above begins
        print(i)
  • descriptor

  • If a class contains three magic methods (_get_) (__set__) (__delete__) Method, this class is called a descriptor
  • The function of descriptor is to manage a member of a class or object in detail. Descriptors manage only one member, while setattr manages all data
  • Data descriptors are classes with three methods at the same time, while non data descriptors do not have three methods at the same time
  • To use a descriptor, you must declare the descriptor before the class
  • Difference between attribute description method and descriptor
  1. Attribute description method__ getattr__, __setattr__, __delattr__ Wait. For the management of all members of the current class / object, the attribute description method is only valid for the current class
  2. Descriptor__ del__,   __ set__,   __ deleate__. Only for the setting of a member of a class / object, the descriptor can be used for different classes
  • How to use descriptor
  1. Define a descriptor in the py file, that is, the descriptor, including the above three magic methods
  2. Then, in the class to be called, the data attribute or function attribute = descriptor, that is, it is handed over to descriptor management,
  3. Finally, in the three magic methods described, you can set the corresponding return value, or set, delete and other operations
  • Property describes how to use the method
  1. Defined in the class. When the conditions are met, the custom getattr method in the class is triggered
  2. If it is not defined, the system built-in getattr method is called
  • s