For a friend who has just come into contact with Python's programming language, when it comes to learning python, how does python
Get Object PropertiesDon't know much, in this article we will explain about
python Get Object PropertiesKnowledge of this.
When we get a reference to an object, how do we know what kind of object it is and what methods it has?
Use Type ()
First, let's determine the object type, using the type () function:
Basic types can be judged by type ():
>>> type (123) <class ' int ' >>>> type (' str ') <class ' str ' >>>> type (None) <type (None) ' Nonetype ' >
If a variable points to a function or class, it can also be judged with type ():
>>> type (ABS) <class ' Builtin_function_or_method ' >>>> type (a) <class ' __main__. Animal ' >
But what type is returned by the type () function? It returns the corresponding class type. If we are to judge in an if statement, we need to compare the type of the two variables with the same types:
>>> type (123) ==type (456) true>>> type (123) ==inttrue>>> type (' abc ') ==type (' 123 ') true> >> type (' abc ') ==strtrue>>> type (' abc ') ==type (123) False
The basic data type can be directly written int,str, etc., but what if you want to determine if an object is a function? You can use the constants defined in the types module:
>>> Import types>>> def fn (): ... Pass...>>> type (FN) ==types. Functiontypetrue>>> type (ABS) ==types. Builtinfunctiontypetrue>>> type (lambda x:x) ==types. Lambdatypetrue>>> type ((x for X in range)) ==types. Generatortypetrue