This is also the sturdy feature of python.
Introspection is the type of object that a program written in an object-oriented language can know at runtime. A simple sentence is the type of object that can be obtained at runtime. Such as type(), dir(), getattr(), hasattr(), isinstance ().
a =[1,2,3]
b ={'a':1,'b':2,'c':3}
c = True
print type(a),type(b),type(c) # <type 'list'><type 'dict'><type 'bool'>
print isinstance(a,list) # True
The reflection mechanism is to dynamically determine the type of an object at runtime, and call object properties, methods, and import modules through strings. It is a string-based event-driven
def hasattr(*args,**kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError."""
pass
We know from the source code comment that it returns whether the object has an attribute with the specified name. And it is judged by calling getattr and catching AttributeError exception. Just like the attribute call above, we can use hasattr(a, "test") to judge. We can also think through the source code comments. Can eval also implement this method?
def has_attr(obj, name):try:eval("obj.%s()"% name)return True
except AttributeError as e:return False
a =Base()ifhas_attr(a,"test"):eval("a.test()")
# Output:
Base
test
test
But this method is flawed, because the test output is twice, because we call test() twice, which is not the same as what we want. If you use hasattr, this function will not be called once in the judgment.
With a function to determine whether the attribute exists, then there must be a function to get the attribute.
def getattr(object, name,default=None): # known special caseof getattr
"""
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."""
pass
From the source code comments, we can know that the attribute named name of the object object is obtained. If the default parameter is provided with object.name, then the default value will be returned when the attribute does not exist. The same is the above example:
a =Base()ifhasattr(a,"test"):
func =getattr(a,"test")func()
# Output:
Base
test
From the example, we can see that hasattr did not call the test function, and what getattr obtained was a function object and did not call it. The a.test() function was executed only when we actively executed func(), which is compared to exec and eval are much more flexible.
Judging and getting properties are there, so setting properties is also needed.
def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value.setattr(x,'y', v) is equivalent to ``x.y = v''"""
pass
Recommended Posts