How do I get the object properties in Python? (example explained)

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.