Introspective reflex
Introspection and reflection are two more specialized terms. Their definitions are as follows:
- Introspection refers to the ability to acquire objects
- Reflection is the ability to manipulate objects
Because Python is a strongly typed dynamic interpretive language, its introspection and reflection are very simple to use.
Sometimes we don't know the properties and methods in the object, especially when we take over other people's projects.
In this case, we cannot directly use object__ dict__ To obtain the attributes and methods of its object (because the inherited attributes cannot be obtained in this way), we should first use introspection to obtain the object information, and then use reflection to manipulate the object, so the learning of introspection and reflection is particularly important.
The following examples are common functions of introspection and Reflection:
function | Return value | describe |
---|---|---|
help(object) | None | Get object documentation help information |
dir(object) | list | Get all the objects that can be Properties and methods of manipulation |
hasattr(object, str) | bool | Returns whether the object has a property or method of the given name |
getattr(object, str, default) | attr | Gets the attribute or method specified in the object. If the attribute or method does not exist, an AttributeError exception will be thrown. If the default value is set, the default value will be returned when the attribute or method does not exist |
setattr(object, str, any) | None | Sets the value of a property or method in an object |
delattr(object, str) | None | Deletes a specified property or method in an object |
issubclass(subClass, parentClass) | bool | Determine whether a class is a subclass of another class |
isinstance(instance, class) | bool | Determines whether an object is an instance of another class |
callable(object) | bool | Determines whether the object is callable |
Example demonstration
help(object) can obtain the help information of the object document.
Return to None:
>>> help(int) Help on class int in module builtins: class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded ...
dir(object) can get all the objects under the object Properties and methods of manipulation.
Return to list:
>>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
hasattr(object, str) can return whether the object has a property or method with a given name.
Return bool:
>>> hasattr(list, "index") True >>> hasattr(list, "items") False
getattr(object, str, default) can obtain the attribute or method specified in the object. If the attribute or method does not exist, an AttributeError exception will be thrown. If the default value is set, the default value will be returned when the attribute or method does not exist:
>>> method = getattr(list, "index") >>> method <method 'index' of 'list' objects> >>> method([1, 2, 3], 2) 1
setattr(object, str, any) can set the value of a property or method in an object.
Return to None:
>>> class A: ... pass ... >>> A.__doc__ None >>> setattr(A, "__doc__", "help message") >>> A.__doc__ help message
delattr(object, str) can delete a specified attribute or method in an object.
Return to None:
>>> class A: ... classAttr = "attr" ... >>> A.classAttr 'attr' >>> delattr(A, "classAttr") >>> A.classAttr AttributeError: type object 'A' has no attribute 'classAttr'
issubclass(subClass, parentClass) can determine whether a class is a subclass of another class.
Return bool:
>>> issubclass(bool, int) True
isinstance(instance, class) can determine whether an object is an instance of another class.
Return bool:
>>> isinstance(1, bool) False >>> isinstance(True, bool) True
Common operation
When you are not sure whether an object has a property or method, you can use hasattr(), getattr(), and callable().
As follows:
import sys class YunPan: """ this is YunPan. You can specify start-up parameters on the command line. If the specified parameter is attribute, this property will be displayed. If the specified parameter is called, the method is performed The parameters you can specify now are: Help: Get help information The method you can specify is: Download: Test Download Features, Parameters -> Str UPLOAD: Test Upload Energy, Parameters -> Str Raises: TypeError: If there is no such method or attribute in the class, it will throw an exception. """ help = __doc__ def __init__(self) -> None: self.attrOrMethod = sys.argv[1] self.fileName = sys.argv[2] if len(sys.argv) > 2 else None self.choices() def download(self): print("downloading file : %s"%self.fileName) def upload(self): print("uploading file : %s"%self.fileName) def choices(self): if not hasattr(self, self.attrOrMethod): raise TypeError("%s not implement method or attributes:%s"%(self.__class__.__name__, self.attrOrMethod)) attrOrMethod = getattr(self, self.attrOrMethod) if callable(attrOrMethod): return attrOrMethod() print(attrOrMethod) if __name__ == "__main__": YunPan()
Test results:
$ python3 .\demo.py help this is YunPan. You can specify start-up parameters on the command line. If the specified parameter is attribute, this property will be displayed. If the specified parameter is called, the method is performed The parameters you can specify now are: Help: Get help information The method you can specify is: Download: Test Download Features, Parameters -> Str UPLOAD: Test Upload Energy, Parameters -> Str Raises: TypeError: If there is no such method or attribute in the class, it will throw an exception. $ python3 .\demo.py download TestFile downloading file : TestFile $ python3 .\demo.py upload TestFile uploading file : TestFile $ python3 .\demo.py func .. TypeError: YunPan not implement method or attributes:func