Day7 object-oriented -- Reflection, day7 object-oriented --

Source: Internet
Author: User

Day7 object-oriented -- Reflection, day7 object-oriented --

Reflection

You can use the following four methods to map strings or modify the status, attributes, and methods when running a program:

1. getattr (object, name [, default])-> value

Get a named attribute from an object; getattr (x, 'y') is equivalent to x. y.
When a default argument is given, it is returned when the attribute doesn't
Exist; without it, an exception is raised in that case.

To determine whether a specified method exists in a class, follow these steps:

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self): print ("% s is eating ...... "% self. name) d = Dog ("alex") choice = input (">> :"). strip () # The user inputs a function to determine whether the function exists, executes it, and reflects it to determine whether to execute print (hasattr (d, choice ))
Run the following command:
>>: Talk
False
>>: Eat
True

We know that sometimes we need to judge whether there is a certain method in the class based on user input, so that we can execute it. How to judge? You can use the hasattr (object, name) method. Above, we have implemented a dynamic judgment method. If yes, True is returned; otherwise, False is returned.

2. getattr (object, name [, default])-> value
Get a named attribute from an object; getattr (x, 'y') is equivalent to x. y.
When a default argument is given, it is returned when the attribute doesn't
Exist; without it, an exception is raised in that case.

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self): print ("% s is eating ...... "% self. name) d = Dog ("alex") choice = input (">> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether to execute print (getattr (d, choice ))
The running result is as follows:
>>: Tall
Traceback (most recent call last ):
File "/home/zhuzhu/Seventh Day/get_attr.py", line 11, in <module>
Print (getattr (d, choice ))
AttributeError: 'dog 'object has no attribute 'tall'
>>: Eat
<Bound method Dog. eat of <__ main _. Dog object at 0x7fecf92428d0>

As can be seen from the above, getattr () is the memory address for obtaining the attribute. If the returned memory address exists, if it does not exist, an error is returned, prompting that this method does not exist in the class.

Since getattr () has a memory address for the return method, add the following brackets:

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self): print ("% s is eating ...... "% self. name) d = Dog ("alex") choice = input (">> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether getattr (d, choice) () is executed )()
The running result is as follows:
>>: Eat
Alex is eating ......

We can see from the above that the program runs normally. Through the above, we can find that hasattr () and getattr () are often used together, And hasattr () determines whether this method exists, getattr () is used for execution. If yes, call getattr () for execution. As follows:

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self): print ("% s is eating ...... "% self. name) d = Dog ("alex") choice = input (">> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether to execute if hasattr (d, choice): ''', which is used in many cases, for example, if a user is asked to enter a function, if the function is executed and does not exist, it indicates that the user does not have this function '''getattr (d, choice) () else: print ("the method you entered does not exist, please check and re-enter :")
The running result is as follows:
>>: Eat # execution Method
Alex is eating ......
>>: Tall # does not exist. The system prompts that the method does not exist.
The method you entered does not exist. Check the method and try again.

From the code above, we can see that the dynamic user input judgment method can be used to determine whether a method exists, executed, and prompts do not exist.

The following figure shows how parameters are implemented:

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self, food): print ("% s is eating ...... % s "% (self. name, food) d = Dog ("alex") choice = input (">> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether to execute if hasattr (d, choice): ''', which is used in many cases, for example, if a user is asked to enter a function, if the function exists and does not exist, it indicates that the user does not have this function '''func = getattr (d, choice) func ("chenronghua") # getattr (d, choice) ("chenronghua") else: print ("the method you entered does not exist. Check the method and enter it again :")
The running result is as follows:
>>: Eat
Alex is eating... chenronghua

You can also determine whether an attribute exists, as shown in the following code. Then, you can determine the pure attribute and obtain the attribute value:

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self, food): print ("% s is eating ...... % s "% (self. name, food) d = Dog ("alex") choice = input (">> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether to execute if hasattr (d, choice): ''', which is used in many cases, for example, if a user is asked to enter a function, if the function exists and does not exist, it indicates that the user does not have this function '''func = getattr (d, choice) print (func) # func ("chenronghua ") # getattr (d, choice) ("chenronghua") else: print ("the method you entered does not exist. Check the method and enter it again :")
The running result is as follows:
>>: Name
Alex

3. setattr (obj, name, value ,/)
Sets the named attribute on the given object to the specified value.

Setattr (x, 'y', v) is equivalent to ''x. y = v''
Add dynamic attributes:

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self, food): print ("% s is eating ...... % s "% (self. name, food) def talk (self): print ("% s is talking ..... "% self. name) def laugh (self): print ("% s is laughing ..... "% self) d = Dog (" alex ") choice = input (" >> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether to execute if hasattr (d, choice): ''', which is used in many cases, for example, if a user is asked to enter a function, if the function exists and does not exist, it indicates that the user does not have this function '''func = getattr (d, choice) print (func) # func ("chenronghua ") # getattr (d, choice) ("chenronghua") else: # setattr (d, choice, laugh) # dynamically Add a property setattr (d, "alex", "sb ") # dynamically Add a property print (getattr (d, "alex "))
The running result is as follows:
>>: Alex
Sb

Add a dynamic method:

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self, food): print ("% s is eating ...... % s "% (self. name, food) def talk (name): print ("% s is talking ..... "% name) def laugh (self): print (" % s is laughing ..... "% self) d = Dog (" alex ") choice = input (" >> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether to execute if hasattr (d, choice): ''', which is used in many cases, for example, if a user is asked to enter a function, if the function exists and does not exist, it indicates that the user does not have this function '''func = getattr (d, choice) print (func) # func ("chenronghua ") # getattr (d, choice) ("chenronghua") else: setattr (d, choice, laugh) # Add an attribute dynamically # setattr (d, "alex", "sb ") # dynamically Add a property print (getattr (d, choice) ("alex "))

In fact, setattr (obj, name_str, attribute/method) is to assign an attribute/method to name_str. If the third parameter is a method, a method is assigned to name_str, if the third parameter is an attribute, assign an attribute to name_str, which is an attribute. getattr (obj, name_str) is used to obtain a string. It is a method and get (obj, name_str) is the memory address of a method. In essence, it is still getattr (). The method depends on whether there is a parameter. If there is a parameter, it is added to the parameter call for execution, if no parameter is specified, brackets are directly added.

4. delattr (obj, name ,/)
Deletes the named attribute from the given object.

Delattr (x, 'y') is equivalent to ''del x. Y''

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self, food): print ("% s is eating ...... % s "% (self. name, food) def talk (name): print ("% s is talking ..... "% name) def laugh (self): print (" % s is laughing ..... "% self) d = Dog (" alex ") choice = input (" >> :"). strip () # The user inputs a function to determine whether the function exists, whether it exists, and whether it exists. Reflection is used to determine whether to execute if hasattr (d, choice): ''', which is used in many cases, for example, if a user is asked to enter a function, if the function exists and does not exist, it indicates that the user does not have this function '''func = getattr (d, choice) print (func) # func ("chenronghua ") # getattr (d, choice) ("chenronghua") else: setattr (d, choice, laugh) # Add an attribute dynamically # setattr (d, "alex", "sb ") # dynamically Add a property getattr (d, choice) ("alex") delattr (d, choice) # Delete the property or method getattr (d, choice) ("alex ")

Delattr (obj, name_str) deletes methods or attributes from an instance.

Reflection:

Hasattr (obj, attr) is used to determine whether an object has a corresponding string.

Getattr (obj, name_str) obtains the memory address of the corresponding method in the obj object based on the string.

Setattr (obj, name_str, z) is equivalent to obj. name_str = z

Delattr (obj, name_str) method or attribute used to delete an instance Summary

 

Class Dog (object): def _ init _ (self, name): self. name = name def eat (self, food): print ("% s is eating ...... % s "% (self. name, food) def talk (name): print ("% s is talking ..... "% name) def laugh (self): print (" % s is laughing ..... "% self) d = Dog (" alex ") choice = input (" >> :"). strip () # user input function, judge whether the function exists, execute, reflection to determine execution set_what = input ("assign that variable to attribute :"). strip () if hasattr (d, choice): getattr (d, choice) else: setattr (d, choice, laugh) v = getattr (d, choice) if type (v) = str: print (v) else: print (v ("alex "))
The running result is as follows:
>>: Alex
Assign the variable to the attribute sb.
Alex is laughing .....
None

 

The above example is a further supplement to setattr (), which is actually to set attributes or methods.

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.