Home Backend Development Python Tutorial Detailed introduction to Python object types

Detailed introduction to Python object types

Jul 19, 2017 pm 04:27 PM
python Operation

                                                                                                                                                                          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
     对象的类型用于描述对象的内部表示及其支持的方法和操作
     创建特定类型的对象,也将该对象称为该类型的实例,实例被创建后,其身份和类型就不可改变
     容器:某对象内包含对其它对象的引用
     
     对象拥有特有的数据属性和方法,使用点运算符调用
            数据:变量
            方法:函数
Copy after login

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
Copy after login

2)Core data types

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

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'
    图解过程
Copy after login

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
            整数和浮点数混合运算的结果是浮点数
Copy after login

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
Copy after login

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 of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles