Object-oriented reflection of Python

Source: Internet
Author: User

First, let's take a look at two built-in functions, isinstance and Issubclass, which determine whether an object is a corresponding type, such as:

obj = ' python ' Print (Isinstance (OBJ,STR))

Determines if obj is a string type, and the result returns True

The latter issubclass determines whether a class is a subclass of another, such as:

Class A:passclass B (A): Passprint (Issubclass (b,a))

Determines whether B is a subclass of a, and the result returns True

Reflection: In fact, its core essence is to use the form of a string to manipulate (Find/Get/delete/Add) members of the object (module), a string-based event-driven!

Python's four important built-in functions: getattr , hasattr , delattr and setattr more fully implement a string-based reflection mechanism. They all operate on the in-memory module and do not modify the source files.

Import Sysclass Commons: @staticmethod def login (): Print ("login page") @staticmethod def Logout (): PR Int ("Exit page") @staticmethod def Home (): Print ("This is the website home page") This_moudle = Sys.modules[__name__]def run (): INP = i Nput ("Please enter the URL of the page you want to visit:"). Strip () if Hasattr (COMMONS,INP): func = GetAttr (COMMONS,INP, ' no this page ') func () Els E:print ("404!") Run ()

From the example above you can see the usage of hasattr and getattr, and the Delattr and SetAttr methods are similar

So why should we use a reflection mechanism?

The benefits are:

1, the implementation of pluggable mechanism (for the code), can be defined in advance interface, interface only after the completion of the actual execution, this implementation of Plug and Play, which is actually a ' late binding ', what meaning? That is, you can write the main logic in advance (just define the interface), and then later to implement the function of the interface

2. Dynamic Import module (based on Reflection current module member)

def run (): INP = input ("Please enter the URL of the page you want to access:"). Strip () modules, Func = Inp.split ("/") obj = __import__ (modules) if HASATTR ( Obj, func): func = GetAttr (obj, func) func () else:print ("404") Run ()

Input form: Please enter the url:commons/home you want to access the page

The result of the execution is: This is the website home page

Here, by the way, the official recommends that the module be imported in the following way

Import Importlibimportlib.import_module (' libraries that need to be imported ')

Next we look at several other python built-in functions __getattr__, __setattr__, __delattr__

class foo:    def __init__ (Self,name):         self.name = name    def __setattr__ (self, key, value): #添加/ Modifying a property triggers its execution          if isinstance (VALUE,STR):             self.__dict__[key] = value             print ("__setattr__")          else:            raise  TypeError ("must be string")     def __getattr__ (Self, item): #只有在使用点调用属性且属性不存在的时候才会触发          print ("getattr--->%s %s"% (Item,type (item)))     def __delattr__ (Self, item): #删除属性的时候会触发           self.__dict__. Pop (item)         print ("__delattr__") f = foo (' Zds ') print ( f.name) f.age =  ' Print (f.age) del f.ageprint (f.__dict__) print (F.XXXXX)

Packaging and licensing

Packaging: Python provides a standard data type and a rich set of built-in methods, but in many scenarios we need to customize our own data types based on standard data types, and add/rewrite methods that use the inheritance we just learned Derived knowledge (other standard types can be processed two times in the following way)

Authorization: Authorization is a feature of packaging, packaging a type is usually some customization of the existing type, this practice can create new, modify or delete the functionality of the original product. Others remain as they are. The authorization process, that is, all updated functionality is handled by a part of the new class, but the existing functionality is granted to the object's default property.

The key to implementing authorization is to overwrite the __getattr__ method.

The following example acts as an exercise:

Customizing your own list type based on authorization requires customizing your own __init__ method,
Customizing your own Append: You can add a string type value to a list only
Customizing the properties of the value in the middle of the display list
The rest of the methods use the list default

Class list (List):     def __init__ (self,obj):         super (). __init__ (obj)     def append (self, p_object):         if not isinstance (P_OBJECT,STR):              raise typeerror ("Must be str type")          super (). Append (p_object)      @property      def mid_value (self):         return self[( SELF.__LEN__ ())//2]    def __getattr__ (Self, item):         if hasattr (List,item):             func = getattr (List,item)              return self.fUNC ()         else:             print ("No This Method") l = list ([1,2,3,4,5,6]) l.append (' 7 ') print (l) print (L.mid_value ) L.insert (0,9) print (L)

The result of the operation is:

[1, 2, 3, 4, 5, 6, ' 7 ']
4
[9, 1, 2, 3, 4, 5, 6, ' 7 ']

Object-oriented reflection of Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.