程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Hasattr(), getattr(), setattr(), delattr() functions of Python reflection mechanism

編輯:Python

The reflex mechanism

Look at me first yeah Java A popular understanding of the reflection mechanism in : There is one in the reflection “ back ” The concept of , So if you want to explain reflection, you have to start with “ just ” Start explaining , generally speaking , When a user uses a class , You should know this class first , Then the instantiated object is generated through this class , however “ back ” It refers to finding classes through objects .

And for Python, If we need to import modules dynamically , And dynamically access the properties and methods in the object , How do you do it? ? Look at the code below .

s = "lib.test.commons"
m1 = __import__(s) # This only dynamically imports lib modular 
m2 = __import__(s, fromlist = True) # fromlist = True, In this way, you can dynamically import by path commons modular 
inp_func = input(" Please enter the function to execute :")
f = getattr(m2, inp_func)() # Add "()" Dynamically executing functions 

It can be seen from the above , Reflection is :

  • In the form of strings , Dynamic import module ;
  • Use the form of string , In object ( modular ) In the operation ( lookup / obtain / Delete / add to ) member , It's a string based event driver !

Reflection mechanism built-in functions

hasattr(obj,name)

Judge an object obj Is there any name Property or name Method , return bool value , Yes name Property return True, Otherwise return to False.

It should be noted that name Wrap it in quotation marks .

class test():
name="xiaohua"
def run(self):
return "HelloWord"
>>> t=test()
>>> hasattr(t, "name") # The objects of judgment are name attribute 
True>>> hasattr(t, "run") # The objects of judgment are run Method 
True

getattr(obj,name[,default])

Get objects obj Property or method , If it exists, print it out , If it doesn't exist , Default values are printed , The default value is optional .
It should be noted that , If it's the method of the returned object , The memory address of the method is returned , If you need to run this method , You can add a pair of parentheses after it .

''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
class test():
name="xiaohua"
def run(self):
return "HelloWord"
>>> t=test()
>>> getattr(t, "name") # obtain name attribute , Print out the existence .
'xiaohua'
>>> getattr(t, "run") # obtain run Method , If it exists, print out the memory address of the method .
<bound method test.run of <__main__.test instance at 0x0269C878>>
>>> getattr(t, "run")() # obtain run Method , Back plus "()" You can run this method .
'HelloWord'
>>> getattr(t, "age") # Get a nonexistent property .
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age","18") # If the attribute does not exist , Returns a default value .
'18'

setattr(obj,name,values)

To object obj Property of , If the attribute does not exist , Create first, then assign .

class test():
name="xiaohua"
def run(self):
return "HelloWord"
>>> t=test()
>>> hasattr(t, "age") # Judge whether the attribute exists 
False
>>> setattr(t, "age", "18") # Property is created when it does not exist , And assignment , But no return value 
>>> hasattr(t, "age") # Attributes exist 
True

delattr(obj,name)

Delete object properties .

in addition ,eval() and exec() Functions are also reflection functions .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved