34th Python Object-oriented reflection (introspection)

Source: Internet
Author: User
Tags ftp client

What is reflection?

The concept of reflection was proposed by Smith in 1982, which refers to the ability (introspection) of a program to access, detect, and modify its own state or behavior. The proposal of this concept soon triggered the research on the application of reflectivity in Computer science field. It is first used in the field of programming language design, and has achieved achievements in Lisp and object-oriented.

Four functions that can be self-reflective, a built-in function of Python
      the following methods apply to classes and objects
      • Take a look at these four ways to use the instance (B1)
#Demo Codeclassblackmedium:feature='Ugly'    def __init__(self, Name, address): Self.name=name Self.address=AddressdefSell_house (self):Print("[%s] is a house-seller, and SB buys it from it."%self.name)defRent_house (self):Print("[%s] is a renter, and SB rents it from it, black"%self.name)#instantiation ofB1 = Blackmedium ('XXX Real Estate','Huilongguan')
    • Hasattr (object, name): Determine whether the object has a name string (' property name ') corresponding to the method or property.

Object: Indicates the name of the property, and is the string form;

 #   Detect data properties   Print  (Hasattr (B1,  " name   ")" #   True # B1. __dict__[' name ']  #   Detect function Properties  print  (Hasattr (B1,  " sell_house    )) #   True  print  (Hasattr (B1,  '  sell_housereqre   ")" #   False  
    • GetAttr (object, Name, Default=none): Gets the property value

Object: The name of the property, the value of the property, the string form;

#gets the specific value of the propertyPrint(GetAttr (B1,'name'))#XXX Real EstatePrint(GetAttr (B1,'Rent_house'))#<bound method Blackmedium.rent_house of <__main__. Blackmedium object at 0x00b52f50>>Func = GetAttr (B1,'Rent_house') func ()#[XXX Real Estate] is a rental son, SB only from it this rent, it blackPrint(GetAttr (B1,'feature'))#Ugly#default ParameterPrint(GetAttr (B1,'sell_house323','without this attribute'))#without this attributegetattr ()#equivalent to B1.sell_house
    • SetAttr (object, name, value): Modify or Add properties and values

Object: The name of the property, the value of the property, the string form;

#setattr Setting Data PropertiesSetAttr (B1,'SB', True) SetAttr (B1,'SB1', 1234) SetAttr (B1,'name',"Wan Shen Real Estate") SetAttr (B1,'feature','Black Intermediary')Print(B1.__dict__)#{' name ': ' Million God property ', ' Address ': ' Huilongguan ', ' SB ': True, ' sb1 ': 1234, ' feature ': ' Black intermediary '}#setattr Setting function PropertiesSetAttr (B1,'funct',LambdaX:x+1) SetAttr (B1,'Funct1',Lambdaself:self.name+"SS")Print(B1.__dict__)#{' name ': ' Million God property ', ' Address ': ' Huilongguan ', ' sb1 ': 1234, ' feature ': ' Black intermediary ', ' funct ': <function <lambda> at 0x02feb618 }#Call the new function propertyPrint(B1.funct (10))# OnePrint(B1.funct1 (B1))#million God real estate SS
    • Delattr (object, name) deletes the attribute.

Object: Represents the objects; Name: The name of the property, in the form of a string

' SB ')   # equals del b1.sb Print (B1. __dict__ #  {' name ': ' Pantheon ', ' address ': ' Huilongguan ', ' sb1 ': 1234, ' feature ': ' Black intermediary '}
      • Look at these four ways to use the class (Blackmedium)
#class is defined, but not instantiatedclassblackmedium:feture='Ugly'    def __init__(SELF,NAME,ADDR): Self.name=name Self.addr=AddrdefSell_hourse (self):Print('"%s" is selling the house, and the idiot buys it.'%self.name)defRent_hourse (self):Print('"%s" is renting a house .'% self.name)
#hasattr ()Print(Hasattr (Blackmedium,'feture'))#TruePrint(GetAttr (Blackmedium,'feture'))Print(SetAttr (Blackmedium,'feture','Black Intermediary'))Print(GetAttr (Blackmedium,'feture'))#Black Intermediarydelattr (Blackmedium,'Sell_hourse')Print(Blackmedium.__dict__)#{' __module__ ': ' __main__ ', ' feture ': ' Black intermediary ', ' __init__ ': <function blackmedium.__init__ at 0x007d1b70>, ' Rent_ Hourse ': <function blackmedium.rent_hourse at 0x007d1ae0>, ' __dict__ ': <attribute ' __dict__ ' of ' BlackMedium ' Objects>, ' __weakref__ ': <attribute ' __weakref__ ' of ' blackmedium ' objects>, ' __doc__ ': None}#

Two. Why use reflection?

Is the project, a project has a number of programmers write, if a write a program to use the class B written, but B leave, have not finished his class, a thought of reflection, using the reflection mechanism a can continue to complete their own code, and so on after the B vacation back to complete the definition of the class and to achieve a desired function.

In short, the reflection advantage is that the interface can be defined in advance, the 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.

Demonstrate:

classftpclient:'FTP client, has not implemented the function specifically'    def __init__(SELF,ADDR):Print("connecting to server [{}]". Format (addr)) Self.addr=Addrf1= FtpClient ('192.168.123.123')#F1.put () # because B has not defined the put () method, so will be an error, can not do so, so need to use the following judgment to doifHasattr (F1,'put'):#determine if there is a put method in the F1Func_get = GetAttr (F1,'put')#If there is, you can get to this methodFunc_get ()#then run this methodElse:    Print("Perform other logic")#If you do not put this method, perform other logic#ResultsConnecting to server [192.168.123.123] Perform other logic
b only defines the interface and has not implemented the function
classftpclient:'FTP client, has not implemented the function specifically'    def __init__(SELF,ADDR):Print("connecting to server [{}]". Format (addr)) Self.addr=Addr#b take a vacation back and implement the Put method    defput (self):Print("file started uploading.")#From try import ftpclientF1 = FtpClient ('192.168.123.123')#f1.put ()ifHasattr (F1,'put'):#determine if there is a put method in the F1Func_get = GetAttr (F1,'put')#If there is, you can get to this methodFunc_get ()#then run this methodElse:    Print("Perform other logic")#If you do not put this method, perform other logic#ResultsConnecting to server [192.168.123.123] The file started uploading
b Take a vacation back, realize a want method

34th Python Object-oriented reflection (introspection)

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.