search
HomeBackend DevelopmentPython TutorialDetailed introduction to Python object types

Detailed introduction to Python object types

Jul 19, 2017 pm 04:27 PM
pythonOperation

                                                                                                                                                                          Everything is an object, and all data stored in the program is an object. Objects are created based on classes. Computers can handle far more than just numerical values, they can also process text, graphics, audio, video, web pages, etc. Different data, different data, need to define different data types.
class refers to a custom type, and type refers to a built-in type. Both represent data types, the names are just different
Each object has an identity, a type and a value. The identity refers to the pointer of the object's location in the memory (the address in the memory), the built-in function id() Returns the identity of an object. The variable name is the name that refers to this specific location
Instantiation: Create an object of a specific type
After an instance is created, its identity and type cannot be changed
If the object value can be modified, it is called a mutable object
If the object value cannot be modified, it is called an immutable object
Container: An object contains references to other objects, such as a list.
Python is a strongly typed language. The type of an object determines the operations that the object can participate in or the methods it supports. That is, the methods exist in the class, and the functions in the object are all found in the class.
Most objects have a large number of unique data properties and methods
Attributes: values ​​related to the object, such as variable names
Methods: Functions that when called will perform certain operations on the object

Python will make commonly used operations in types
1. Built-in methods
2. Syntactic sugar, automatic touch methods

Python object types and their operations

基本要点:
    程序中储存的所有数据都是对象(可变对象:值可以修改   不可变对象:值不可修改)
    每个对象都有一个身份、一个类型、一个值
        例:
            >>> a1 = 'abc'
            >>> type(a1)
            str
                创建一个字符串对象,其身份是指向它在内存中所处的指针(在内存中的位置)
                a1就是引用这个具体位置的名称
                使用type()函数查看其类型
                其值就是'abc'
     自定义类型使用class
     对象的类型用于描述对象的内部表示及其支持的方法和操作
     创建特定类型的对象,也将该对象称为该类型的实例,实例被创建后,其身份和类型就不可改变
     容器:某对象内包含对其它对象的引用
     
     对象拥有特有的数据属性和方法,使用点运算符调用
            数据:变量
            方法:函数

1)Identity and type of object

两个对象比较:
    1、值比较:对象中的数据是否相同;
    2、身份比较:两个变量名引用的是否为同一对象;
    3、类型比较:两个对象的类型是否相同;
注意:
    内置函数id()可返回对象的身份即在内存中的位置
    is比较两个对象的身份
    type()返回对象的类型

        例:
            >>> num1 = 5
            >>> num2 = 6
            >>> num1 == num2                值比较
            False                   
            >>> num1 is num2                身份比较
            True
            >>> type(num1) is type(num2)    类型比较
            True

2)Core data types

    数字:int, long, float, complex(复数), bool
    字符:str, unicode
    列表:list
    字典:dict
    元组: tuple
    文件:file
    其它类型:集合(set), frozenset, 类类型, None

3)Type conversion

        str(), repr()或format():将非字符型数据转换为字符;
        int():                   转为整数
        float():                 转为浮点数
        list(s):                 将字串s转为列表
        tuple(s):                将字串s转为元组
        set(s):                  将字串s转为集合
        frozenset(s):            将字串s转换为不可变集合;
        dict(d):                 创建字典;其d必须是(key, value)的元组序列

例:
    >>> str1 = 'hello,fanison'
    >>> list(str1)
    ['h', 'e', 'l', 'l', 'o', ',', 'f', 'a', 'n', 'i', 's', 'o', 'n']
    >>> tuple(str1)
    ('h', 'e', 'l', 'l', 'o', ',', 'f', 'a', 'n', 'i', 's', 'o', 'n')
    >>> set(str1)
    set(['a', 'e', 'f', 'i', 'h', 'l', 'o', ',', 's', 'n'])       特别注意!!!去重
    >>> l1=[('a',1),('b',2),('c',3)]
    >>> list(l1)
    {'a': 1, 'c': 3, 'b': 2}
    
补充例题:
        >>> a = 'ABC'
        >>> b = a
        >>> a = 'XYZ'
        >>> print a  b
        'XYZ'  'ABC'
    图解过程

Detailed introduction to Python object types

##4)Number Type operations

    5种数字类型:整型、长整型、浮点型、复数、布尔型
    所有数字类型均不可变
        >>> a = 10    # 整型 
        >>> b = 1.5   # 浮点型
        >>> c = True  # 布尔型
        >>> d = 5+2j  # 复数
        例:
            >>> 1 + 2    
            3
            >>> 1.0 + 2
            3.0
            >>> 11 % 4    
            3
            >>> 11.0 / 4     
            2.75
            整数和浮点数混合运算的结果是浮点数

Detailed introduction to Python object types

5) Boolean type

    bool(布尔型)之所以属于数字类型,是因为bool是int的子类。
            >>> int(True)
            1
            >>> int(False)
            0
            >>> bool(1)
            True
            >>> bool(-1)
            True
            >>> bool(0)
            False
        结论:
            bool 转 int时, Ture-->1, False-->0
            int 转 bool时, 非0-->True, 0-->False
    
    与运算:只有两个布尔值都为 True 时,计算结果才为 True。        
        >>> True and True   
        True
        >>> True and False
        False
        >>> False and True
        False
        >>> False and False
        False
    或运算:只要有一个布尔值为 True,计算结果就是 True。        
        >>> True or True
        True
        >>> True or False
        True
        >>> False or True
        True
        >>> False or False
        False
    非运算:把True变为False,或者把False变为True:        
        >>> not True
        False
        >>> not False
        True
    
    注意:1、任何非0数字和非空对象都为真;
          2、数字0、空对象和特殊对象None均为假;
    
    and 和 or 运算的一条重要法则:短路计算。
            1. 在计算 a and b 时,如果 a 是 False,则根据与运算法则,整个结果必定为 False,因此返回 a;如果 a 是 True,则整个计算结果必定取决与 b,因此返回 b。    
            2. 在计算 a or b 时,如果 a 是 True,则根据或运算法则,整个计算结果必定为 True,因此返回 a;如果 a 是 False,则整个计算结果必定取决于 b,因此返回 b。   
            所以Python解释器在做布尔运算时,只要能提前确定计算结果,它就不会往后算了,直接返回结果。
    例:
       >>> a = 'python'
       >>> print 'hello,', a or 'fanison'
       hello,python
       >>> b = ''
       >>> print 'hello,', b or 'fanison'
       hello,fanison

The above is the detailed content of Detailed introduction to Python object types. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor