Detailed Explanation of Object Information Obtained by python

  • 2021-11-14 06:12:06
  • OfStack

1. Get the object type. The basic type can be judged by type ().


>>> type(123)
<class 'int'>
>>> type('str')
<class 'str'>
>>> type(None)
<type(None) 'NoneType'>

2. If you want to get all the properties and methods of an object, you can use the dir () function to return list containing the string.


>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

Extension of knowledge points:

Use type ()

First, let's determine the object type, using the type () function:

Basic types can be judged by type ():


>>> type(123)
<type 'int'>
>>> type('str')
<type 'str'>
>>> type(None)
<type 'NoneType'>

If a variable points to a function or class, it can also be judged by type ():


>>> type(abs)
<type 'builtin_function_or_method'>
>>> type(a)
<class '__main__.Animal'>

But what type does the type () function return? It returns the type type. If we want to judge in the if statement, we need to compare whether the type types of two variables are the same:


>>> type(123)==type(456)
True
>>> type('abc')==type('123')
True
>>> type('abc')==type(123)
False

However, this writing is too troublesome. Python defines constants for each type type and puts them in types module. Before using them, you need to import:


>>> import types
>>> type('abc')==types.StringType
True
>>> type(u'abc')==types.UnicodeType
True
>>> type([])==types.ListType
True
>>> type(str)==types.TypeType
True


Related articles: