Python object type checking and method acquisition guide
When writing flexible and robust Python code, we often encounter objects of "unknown origin" - passed in from the outside, dynamically generated, or need to adapt to multiple types. Getting object information (types, properties, methods) becomes the first step: it can help us avoid errors, optimize branch logic, and even unlock the magic of dynamic calls. This article will systematically introduce type checking, reflection three-piece set and practical applications.
1. Type checking
1.1 Basic but "not inherited"type()
type()It is Python's built-in precise type detector. It will strictly return the current class of the object, regardless of inheritance relationships. Suitable for "non-inheritance" scenarios such as checking basic data types and metatypes of functions/classes themselves:
type()Inheritance relationship will not be recognized! The instance type of the subclass will not be equal to the parent class. Never use it when involving inheritance chains.
1.2 "Precise segmentation" of function family:typesmodule
When we need to check not ordinary class instances, but various function-related types (ordinary functions, anonymous functions, generators, built-in functions, etc.), we can use the standard library directlytypesPredefined type constants in:
1.3 Inheritance friendlyisinstance()
In oop, parent classes can accept subclass instances (the basis of polymorphism). Must be used at this timeisinstance(obj, class_info), it will checkobjIs itclass_infoAn instance of ** itself or any of its subclasses **.
The second parameter can also be passed in a type tuple to check multiple types at once:
Unless must strictly match the current class (for example, subclasses are explicitly prohibited from participating), please use it first in 99% of cases.isinstance()!
2. Get the properties and methods of the object
The type is just the entrance. Next we need to know what capabilities this object has - what methods it can call, what public properties it has, and even how it needs to be dynamically manipulated at runtime.
2.1 A clear view:dir()
dir(obj)Returns an ordered string list, each string corresponds to a property name or method name of the object. Which start and end with double underscore (such as__len__) are Python's "special methods/properties" that usually correspond to built-in operations:
2.2 Dynamic search, retrieval and setting: three-piece reflection set
Python is a dynamic language that allows you to obtain and modify the properties and methods of objects at runtime (not compile time). This is "reflection".
Simply put, it is the ability of a program to inspect and modify the structure and behavior of itself or other objects while it is running.
The core tools arehasattr()、getattr()andsetattr():
3. Practical application examples
Reflection and type checking are often used together to make code more flexible and Pythonic.
3.1 Duck Type: Only about "ability", not "identity"
There is a famous saying in Python: "If it walks like a duck and quacks like a duck, then it is a duck." - This is duck typing: we do not check the specific type of the object, only check whether it has the methods we need.
For example, write a genericread_datafunction, as long as the object hasread()The method is called directly, otherwise it is converted into a string:
3.2 Dynamically calling methods based on data type
Suppose we have a processor, and text and numbers require different processing logic. combineisinstance()andgetattr()Can be flexibly scheduled and even replace defective methods dynamically:
Note: Boolean values in Python are
intsubclass ofTrueEquivalent to1, and therefore will be captured by the digital branch.
4. Summary
The following table summarizes the key techniques for obtaining object information:
:::note Final suggestions
- Although reflection is powerful, it will reduce readability and increase debugging difficulty, so don’t abuse it!
- Prioritize following the duck typing principle and focus on the "ability" of the object rather than the "identity";
- If you must check the type, default to
isinstance(),keep awaytype()。 :::

