Câu hỏi phỏng vấn Python
Câu hỏi

What is introspection/reflection and does Python support it?

Câu trả lời

Introspection in programming refers to the ability of a program to examine the type or properties of an object at runtime. Reflection takes this a step further by allowing a program to modify its own structure and behavior during execution. Python, being a dynamically-typed language, supports both introspection and reflection.

Introspection can be used in Python to obtain information about objects, such as their type, attributes, and methods, at runtime. This can be achieved using built-in functions like type(), dir(), getattr(), hasattr(), and isinstance(). For example, type(obj) returns the type of obj, dir(obj) lists the attributes and methods of obj, and getattr(obj, 'attr') retrieves the value of attr from obj if it exists.

Reflection in Python allows for more advanced manipulation of objects. It enables the creation, modification, and deletion of classes, attributes, and methods at runtime. For instance, you can use the setattr() function to set an attribute on an object, or the delattr() function to delete an attribute. Python's types module can be used to dynamically create new types of objects, and the exec() function can execute Python code that is constructed as a string.

Python's introspection capabilities are particularly useful for debugging, developing generic functions, and working with objects in a dynamic manner. Reflection, on the other hand, is a powerful feature that en...

middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is Lambda Functions in Python?

senior

What is the purpose of the single underscore _ variable in Python?

junior

What is Negative Index in Python?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào