Python learning note _ Python object

Source: Internet
Author: User
Tags type null

Python learning note _ Python object

Python learning note _ Python object standard type other built-in type object and type object Python Null Object None standard type operator object Value Comparison Object Identity comparison boolean type standard type built-in function typeObj cmpobj1 obj2 strobj reprobj typeobj isinstanceobj standard-type classified storage model update model access model unsupported type

Python learning note _ Python object

First, let's understand a common meaning. What isObject? In fact, no matter what language the object is in, suchC++,PythonIt refers to a type of memory, and the object stores the corresponding data.

Python object

All Python objects have three features:Identity,Type,Value
-Identity: Each object has a unique ID to identify itself, just like the storage address of the object in the memory, which is unique and cannot be shared. You can use built-in functions to identify any object.id()To obtain

X = 1 print id (x) # running result: 163449008
Type: Because Python is a dynamic type, the type of the object should be saved in an object to determine what operations the object performs. We can use built-in functions type()To obtain the object type.
Number1 = 1str1 = 'Hello world' print type (number1) print type (str1) # running result #
  
   
#
   
  
ValueThe data items represented by objects are stored in the memory without any difference. 1000001, If yes strType, it is interpreted 'A'If it is an integer, it is interpreted 65

Object Attributes: Some objects have attributes, values, or associated executable code. The most common attributes are functions and methods.

Standard numeric IntegerInteger BooleanBoolean Long integerLong Integer Floating point real numberFloating Point Type Complex numberPlural StringString ListList TupleTuples DictionarryDictionary other built-in type Null Object (None) file set/Fixed Set function/method module class type object and type object

As mentioned before, when an object determines which operations can be performed by its type, the type is the best place to store these operations. Therefore, it is more suitable to describe a type with an object than a string.

type()The built-in function returns a type object, but this object is displayed as a string.

Print type (10) print type (10) # running result :#
  
   
#
   
  

All types of objects aretypeIt is also the default Meta class for all types of root and all Python standard classes.

Python Null Object -- None

NoneThere is only one value. It does not support any computation and does not have any built-in methods.
Each object is bornTrueOrFalseValue.
The Boolean value of the following object isFalse:

None False all numbers 0 0 0.0 0L 0.0 + 0.0j "" [] () {}
Except for the above value, all other values are TrueComparison of object values of standard operators

The comparison of object values directly returns a Bool object, and the comparison methods of various types of objects are also different ., The numeric type is compared based on the value size and symbol, and the string is compared based on the Character Sequence.

Object Identity comparison

In python, an object is usually created in the memory first, and then the reference of this object is assigned to the variable, and the object is operated by reference.

X = 3.14 # create a 3.14 floating point object and assign the reference value to the variable x

In many cases, the reference of an object is passed to the variable. to check whether two variables point to the same variable at the same time, we can use built-in functions.id()To compare the two variables pointing to the objectidEqual or usedisOris notTo compare whether two variables point to the same object.

Example:

X = 3.14y = xprint id (x) = id (y) print x is y # And id (x) = id (y) print x is not y # And id (x )! = Same as id (y)

Running result:
True
True
False

Example:

X = 3.14y = 1.0 + 2.14 print x is y # although the value is the same, it does not point to the same object

Running result:
False

Boolean Type

When multiple Boolean conditions need to be determined by phone,PythonThe following statements are provided for us:

Operator Function
And Logic and
Or Logic or
Not Non-logical
Standard built-in functions

Except operators,PythonSome built-in functions are also provided for these basic information:

Function Function
Cmp (obj1, obj2) Compare whether two objects are equal
Repr (obj) Returns the string representation of an object.
Str (obj) Returns the string representation of an object for the purpose of good readability.
Type (obj) The type of the returned object. The returned type is a type object.
Type (Obj)

type()Built-in functions are used to return the type of an object.

print type(1)print type('Hello World')

Running result:

Cmp (obj1, obj2)

cmp(obj1 , obj2)Is used to compare two objects

Returned results Comparison
Positive Integer Obj1> obj2
0 Obj1 = obj2
Negative integer Obj1 <obj2

The value returned by the comparison above can be understoodobj1 - obj2Returned results

Example:

X, y = 1, 2 print cmp (x, y) # running result:-1
Str1, str2 = 'xyz', 'abc' print cmp (str1, str2) # running result: 1
Str (obj) & repr (obj)

The two built-in functions abovestr(obj)Andrepr(obj)Both return the strings of an object, but these two built-in functions are different:

str(obj): Is used to return a readable string. The target user is a programmer. repr(obj): Is used to return Python Virtual MachineThe string that you can understand is intended for users Python Virtual Machine, repr(obj)The returned string can be eval(str)Reevaluate! That is, this statement is valid. obj == eval(repe(obj))

In general, it isrepr(obj)YesPython is friendly,str(obj)Is user-friendly, but in many casesstrAndreprThe output is the same.

Print str (1) print repr (1) # running result: #1 #1
Type (obj) & isinstance (obj)

type(obj)Can return anyPythonObject type, not limited to standard type
Example:

For standard types

Print type ('') # running result:
  
   
Print type ({}) # running result:
   
  

For custom types

Class Foo: passfoo = Foo () class Bar (object): passbar = Bar () print type (Foo) # running result:
  
   
Print type (foo) # running result:
   
    
Print type (Bar) # running result:
    
     
Print type (bar) # running result:
     
    
   
  

To determine the object type, use the following statement:

# Method 1if type (num) = type (0 ):... # method 2 import typesif type (num) = types. intType :... # method 3if type (num) is types. intType :... # Because there is only one object at run time to represent the integer type # Method 4 from types import IntTypeif type (num) is IntType :... # method 5if isinstance (num, int ):...
Standard category

There are three different models that can help us classify basic types:

Storage Model update model access model Storage Model

In the storage model, we can store multiple objects by type. There are two types of objects:

Scalar storage type: only the type of a single literal object can be saved. container storage type: the type that can accommodate multiple objects
Category Python type
Scalar storage type Numeric (All numeric types), string (all are text, because python has no character type)
Container Type List, tuples, and dictionaries
Update Model

InpythonThe types can be changed but cannot be changed. objects that run the changes allow their values to change, while unchangeable objects do not allow their values to be changed.

Category Python type
Variable type List, Dictionary
Unchangeable type Number, string, and tuples

What? Numbers and strings cannot be changed? What is the change?

str1 = 'Hello World'str1 = 'Hello Moto'

Yes, the value of the above variable has indeed changed, but the variable does not represent the object. The first value assignment is'Hello World'Is assignedstr1And the second value assignment statement is'Hello Moto'Is assignedstr1, Two string objects'Hello World'And'Hello Moto'The value of is not changed!

Access Model

There are three access methods in the access model:Direct Access,SequenceAndIng

Direct Access: Direct access to non-container objects Sequential access: Elements in the container can be accessed from the index Sequence starting from 0. Ing access: Access through a unique key
Category Python type
Direct Access Number
Sequential access String, tuples, list
Ing access Dictionary
Unsupported type

PythonThere are some common but unsupported types:

Char and byte pointer int, short, long single precision Floating Point Number

 

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.