Python-object-oriented advanced, python-advanced
I. isinstance (obj, cls) and issubclass (sub, super)
1. isinstance (obj, cls), check whether obj is an object of the cls class
1 class A: 2 pass3 4 obj = A () 5 print (isinstance (obj, A) 6 7 # running result 8 # True
2. issubclass (sub, super), check whether the sub class is a derived class of the super class (subclass)
1 class A: 2 pass 3 4 class B (A): 5 pass 6 7 print (issubclass (B, A) 8 9 # running result 10 # True
Ii. Reflection
1. What is reflection?
The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect, and modify its own state or behavior (introspection ). The proposal of this concept soon led to research on application reflectivity in the computer science field. It was first adopted by the design field of programming language, and has made achievements in Lisp and object-oriented aspects.
2. Reflection in python object-oriented:Operations on Object-related attributes in the form of strings. Everything in python is an object (reflection can be used ).
1 class People: 2 country = 'China' 3 def _ init _ (self, name, age): 4 self. name = name 5 self. age = age 6 7 def info (self): 8 print ('% s is % d years old' % (self. name, self. age) 9 10 p = People ('jack', 18) 11 12 # hasattr (obj, name), check attributes 13 print (hasattr (p, 'info ')) # Check whether the object p has the 'info' attribute. The result is True14 print (hasattr (p, 'name') # Check whether the object p has the 'name' attribute, result: True15 16 # getattr (obj, name) gets attribute 17 print (getattr (p, 'name') # obtains the 'name' attribute of object p. Result: p is returned. name value, that is, jack18 print (getattr (p, 'info') # obtain the 'info' attribute of object p. Result: The value of p.info is returned, 19 # Memory Address bound to method info: <bound method People.info of <__main __. people object at 0x000001B64317ABE0> 20 getattr (p, 'info') () # Because getattr returns the memory address of the object method attribute, you can call it by adding (). The result is: jack is 18 years old21 22 # setattr (x, y, v) set attribute 23 setattr (p, 'age', 21) # modify the 'age' attribute of object p. Result: p. the value of age changes to 2124 setattr (p, 'sex ', 'male') # adds the 'sex' attribute of object p. The result is: p. the sex value is male25 print (p. _ dict _) # view the data attributes of object p. Result: {'name': 'jack', 'age': 21, 'sex ': 'male'} 26 27 # delattr (x, y) delete attribute 28 delattr (p, 'sex ') # Delete the 'sex' attribute 29 print (p. _ dict _) # result: {'name': 'jack', 'age': 21}Four functions for introspection: hasattr (obj, name); getattr (obj, name); setattr (x, y, v); delattr (x, y)
1 # The class is also an object. 2 class Foo (object): 3 staticField = "old boy" 4 5 def _ init _ (self): 6 self. name = 'wupeiqi '7 8 def func (self): 9 return 'func' 10 11 @ staticmethod12 def bar (): 13 return 'bar' 14 15 16 print (getattr (Foo, 'staticfield ') # obtain the 'staticfield' attribute of the class. Result: old boy17 18 print (getattr (Foo, 'function') # obtain the 'function' attribute of the class. Result: <function Foo. func at 0x0000018156FBB950> 19 print (getattr (Foo, 'func') ('self ') # Add () to call the method. Result: func20 21 print (getattr (Foo, 'bar') # obtain the 'bar' attribute of the class. Result: <function Foo. bar at 0x00000192D2AFB9D8> 22 print (getattr (Foo, 'bar') () # Add () to call the method. The result is: barClass is also an object that can be used for reflection
1 # reflection on current module Member 2 #! /Usr/bin/env python 3 #-*-coding: UTF-8-*-4 5 import sys 6 7 8 def s1 (): 9 print ('s1 ') 10 11 12 def s2 (): 13 print ('s2') 14 15 16 this_module = sys. modules [_ name _] 17 18 print (this_module) # result: <module '_ main _' from '...... '> 19 print (hasattr (this_module, 's1') # result: True20 print (getattr (this_module, 's2') # result: <function s2 at 0x0000020590EAB8C8> 21 getattr (this_module, 's2 ') () # result: s2The module is also an object that can be used for reflection.
3. Benefits of reflection
Benefit 1: Implement pluggable Mechanism
There are two programmers, lili and egon. lili needs to use the class written by egon when writing a program, but egon has gone to honeymoon with his girlfriend, the class he wrote is not complete yet. lili thinks of reflection and uses the reflection mechanism lili to continue to complete his own code, after egon's honeymoon comes back, it will continue to define the class and implement the features lili wants.
In short, the advantage of reflection is that you can define the interface in advance, and the interface will be actually executed only after it is completed, which implements plug-and-play, this is actually a kind of 'post-binding '. What does it mean? That is, you can write the main logic (only define interfaces) in advance, and then implement the interface functions later.
1 class FtpClient: 2' ftp client, but there are still some specific functions '3 def _ init _ (self, addr ): 4 print ('connecting to server [% s]' % addr) 5 self. addr = addr 6 7 ############################### 8 # lili is not affected code 9 10 from module import FtpClient11 f1 = FtpClient ('2017. 168.1.1 ') 12 if hasattr (f1, 'get'): 13 func_get = getattr (f1, 'get') 14 func_get () 15 else: 16 print ('----> this method does not exist') 17 print ('process other logics ')
Benefit 2: dynamic import module (based on reflection of current module members)
1 # Two Methods for importing user input modules, officially recommended method 2 2 # method 1 3 m = input ('input your module: ') # user input module name to import, take the time module as an example. 4 m1 = _ import _ (m) 5 print (m1) # result: <module 'time' (built-in)> 6 print (m1.time () # result: 1493023753.0157707, current time 7 8 # method 2 9 import importlib # Pilot import importlib Module 10 t = importlib. import_module (m) 11 print (t) # result: <module 'time' (built-in)> 12 print (t. time () # result: 1493023753.0238242, current time
3. built-in attr
1 class Foo: 2 x = 1 3 def _ init _ (self, y): 4 self. y = y 5 6 def _ getattr _ (self, item): 7 print ('----> from getattr: the property you are looking for does not exist ') 8 9 def _ setattr _ (self, key, value): 10 print ('----> from setattr') 11 # self. key = value # This infinitely recursion 12 self. _ dict _ [key] = value # Use it 13 14 def _ delattr _ (self, item): 15 print ('----> from delattr ') 16 # del self. item # infinite recursion 17 self. _ dict __. pop (item) # use it for 18 19 #__ setattr _ adding/modifying properties will trigger its execution 20 f1 = Foo (10) # Because _ setattr __, any value assignment operation will trigger it to run 21 print (f1. _ dict _) # result: ----> from setattr {'y ': 10} 22 f1.z = 3 # Add attribute 23 print (f1. _ dict _) # result: ----> from setattr {'y': 10, 'z ': 3} 24 25 #__ delattr _ 26 f1. _ dict _ ['a'] = 3 # We can directly modify the attribute dictionary, 27 del f1.a # Trigger _ delattr _ 28 print (f1. _ dict _) # result: ----> from delattr {'y ': 10, 'z': 3} 29 30 #__ getattr _ the 31 print (f1.y) # Attribute will be triggered only when the object call attribute does not exist. Result: 1032 f1.a # property a does not exist, trigger _ getattr __, result: ----> from getattr: the property you are looking for does not exist
Iv. Standard secondary processing type (packaging)
Packaging: python provides you with standard data types and rich built-in methods. In fact, in many scenarios, We need to customize our own data types based on standard data types, add/Rewrite methods, which use the inherited/derived knowledge we just learned (other standard types can be processed through the following method)
1 # standard type of secondary processing (based on inheritance) 2 class List (list): # inherit all the attributes of list, you can also derive your own new, for example, append and mid 3 def append (self, p_object): 4' derive your own append: add the type check '5 if not isinstance (p_object, int ): 6 raise TypeError ('ust be int') 7 super (). append (p_object) 8 9 @ property10 def mid (self): 11' add your own attribute '12 index = len (self) // 213 return self [index] 14 15 l = List ([1, 2, 3, 4]) 16 print (l) 17 l. append (5) 18 print (l) # result: [1, 2, 3, 4, 5] 19 # l. append ('200') # error, must be int type 20 21 print (l. mid) # result: 322 23 # all other methods inherit the 24 l of list. insert (0,-123) # insert element 25 print (l) # result: [-123, 1, 2, 3, 4, 5] 26 l. clear () # clear list 27 print (l) # result: []
Authorization: authorization is a feature of packaging. Packaging A type is usually customized for existing types. In this way, you can create, modify, or delete functions of the original product. Others are kept as they are. The authorization process is that all updated functions are processed by a part of the new class, but existing functions are authorized to the default attributes of the object.
The key to implementing authorization is to overwrite the _ getattr _ method.
1 # authorization Example 2 import time 3 4 5 class FileHandle: 6 def _ init _ (self, filename, mode = 'R', encoding = 'utf-8 '): 7. self. file = open (filename, mode, encoding = encoding) # obtain the file handle 8 9 def write (self, line): # redefine the write method, the time added function is 10 t = time. strftime ('% Y-% m-% d % t') 11 self. file. write ('% s % s' % (t, line) 12 13 def _ getattr _ (self, item ): # When other attributes of file operations cannot be found in the FileHandle class, _ getattr _ 14 return getattr (self. file, item) 15 16 17 f1 = FileHandle(' B .txt ', 'W +') create a new file B .txt, obtain the file handle, and assign it to the object f118 f1.write ('Hi ') # Call the custom method write19 f1.seek (0) # reset the file location in the beginning of the text, trigger _ getattr __, call 20 print (f1.read () normally # print the file content, trigger _ getattr __, which is called normally. Result: 17:30:37 Hello 21 f1.close () # close the file and trigger _ getattr __, which is called normally
References:
1. http://www.cnblogs.com/linhaifeng/articles/6204014.html