[Python] Types and objects

Source: Internet
Author: User
Tags access properties class definition instance method shallow copy string methods

1. Terminology

All data stored in the program is an object. Each object has an identity, a type, and a value. An object's identity can be thought of as a pointer to its location in memory, and the variable name is the name that refers to that particular location.
The type of an object is also known as a category, which describes the internal representation of an object and the methods and operations it supports. When you create an object of a specific type, you sometimes refer to that object as an instance of that type. Once an instance is created, its identity and type cannot be changed. If the value of an object can be modified, called a mutable object, the inverse is called an immutable object. If an object contains references to other objects, it is referred to as a container or a collection.
Most objects have a large number of unique data properties and methods. The property is the value associated with the object. The method is the function that will perform certain operations on the object when called. Use point "." operator to access properties and methods.

2. Identity and type of object

The built-in function ID () returns the identity of an object, and the return value is an integer. The IS operator is used to compare the identities of two objects. The built-in function type () returns the type of an object. For example:

def compare(a, b):    if a is b:        # 同一个对象    if a == b:        # 具有相同的值    if type(a) is type(b):        # 具有相同类型

The type of the object itself is also an object, called the class of the object. All types of objects have a specified name that can be used to perform type checking, for example:

if type(s) is list:    s.append(item)if type(d) is dict:    d.update(t)

A better way to check the type is with the built-in function isinstance (object, type), for example:

if isinstance(s, list):    s.append(item)if isinstance(d, dict):    d.update(t)

Because the Isinstance () function implements inheritance, it is the preferred way to check all Python object types.

3. Reference counting and garbage collection

All objects have a reference count. Whether you assign a new name to an object or put it in a container, the object's reference count increases, for example:

a = 37 # 创建值为37的对象b = a # 增加37的引用计数c = []c.append(b) #增加37的引用计数

This example creates an object that contains a value of 37, a simply refers to the name of the newly created object, and when a is assigned to B, B becomes the new name of the same object, and the reference count of the object is incremented. Similarly, when B is placed in a list, the reference count of the object is incremented again.
When a del statement is used or a reference is out of scope (or is re-assigned), the object's reference count is reduced, for example:

del a # 减少37的引用计数b = 42 #减少37的引用计数c[0] = 2.0 #减少37的引用计数

Use the Sys.getrefcount () function to get the current reference count of an object, for example:

a = 37import sysprint(sys.getrefcount(a))

In most cases, reference counts are much larger than guesses, and for immutable data, such as numbers and strings, the interpreter proactively shares objects in different parts of the program in order to conserve memory.
When the reference count of an object is zeroed, it is disposed of by the garbage collection mechanism. In some cases, there may be a circular dependency between many objects that are no longer in use, for example:

a = {}b = {}a[‘b‘] = bb[‘a‘] = adel adel b

In the above example, the DEL statement will reduce the reference count of A and B and destroy the name used to refer to the underlying object. However, because each object contains a reference to another object, the reference count is not zeroed and the object is not destroyed, resulting in a memory leak. To solve this problem, the interpreter periodically executes a loop detector that searches for the non-accessible objects ' loops and deletes them.

4. References and replication

When the program makes an assignment such as a = B, a reference to B is created. For immutable objects such as numbers and strings, this assignment actually creates a copy of B. However, the reference behavior for mutable objects, such as lists and dictionaries, can be completely different, for example:

a = [1, 2, 3, 4]b = aprint(b is a) # Trueb[2] = -100print(a[2]) #-100

Because A and B refer to the same object, modifying either of these variables will affect the other. Therefore, you must create a copy of the object instead of a new reference. For container objects such as lists and dictionaries, you can use two kinds of copy operations: Shallow copy and deep copy. Shallow copy creates a new object, but it contains a reference to the items contained in the original object, for example:

a = [1, 2, [3, 4]]b = list(a)print(b is a) #Falseb.append(100)print(b) # [1, 2, [3, 4], 100]print(a) # [1, 2, [3, 4]]b[2][0] = -100print(b) # [1, 2, [-100, 4], 100]print(a) # [1, 2, [-100, 4]]

Deep copy creates a new object and recursively copies all of the objects it contains. You can use the Copy.deepcopy () function in the standard library to do the work, for example:

import copya = [1, 2, [3, 4]]b = copy.deepcopy(a)b[2][0] = -100print(b) # [1, 2, [-100, 4]]print(a) # [1, 2, [3, 4]]
5. A built-in type that represents data

There are about 12 data types that you can use to represent most of the data used in your program. As shown in the following table:

/tr>
type category type name description
none Type (none) null object none
number int integer
number float floating point
number complex plural
number bool boolean value
sequence str string
sequence list list
sequence tuple tuple
sequence range created integer range
map range integer range created
collection set mutable set
collection frozense T Immutable collection

The

None type represents an object that has no value and is represented as none in the program. If a function does not display a return value, the object is returned. None is often used for the default value of an optional parameter, so that the function detects whether the caller actually passed a value for the parameter.
Python uses 4 numeric types: Boolean, Integer, floating-point, and complex. All numeric objects are signed except for Boolean values. All numeric types are immutable. Numeric types have a number of properties and methods that simplify operations involving mixed arithmetic. To be compatible with rational numbers, integers use attributes X.numerator and x.denominator. In order to be compatible with complex numbers, integers or floating-point numbers y have properties y.real and Y.imag, as well as Method Y.conjugate (). Use Y.as_interger_ratio () to convert a floating-point number y to a pair of integers in fractional form. Method Y.is_interger () is used to test whether the floating-point number y represents an integer value. Floating-point numbers can be used in low-level binary form by means of Y.hex () and Y.fromhex (). The
sequence represents a collection of ordered objects that are indexed as non-negative integers, including strings, lists, and tuples. The following tables are supported for all sequences:

Project Description
S[i] Returns the element of a sequence I
S[I:J] Returns a slice
S[i:j:stride] Returns an extended slice
Lens (s) Number of elements in s
Min (s) The minimum value in s
Max (s) The maximum value in s
Sum (s [, initial]) The and of the items in S
All (s) Check if all items in s are true
Any (s) Check if any of the items in S are true

The following table applies to variable sequences:

Project Description
S[i] = V Project Assignment Value
S[I:J] = t Slice Assignment
S[i:j:stride] = t Extended Slice Assignment
Del S[i] Item deletion
Del S[i:j] Slice Delete
Del S[i:j:stride] Extended Slice Deletion

The list supports the following table:

Method Description
List (s) Convert S to a list
S.append (x) Appends a new element x to the end of S
S.extend (x) Append a new list to the end of S
S.count (x) Calculates the number of occurrences of x in S
S.index (x [, start [, stop]]) Find the location where X first appears
S.insert (i, X) Insert X at index i
S.pop ([i]) Returns the element I and removes it from the list, omitting I returns the last element in the list
S.remove (x) Search for x and remove it from S
S.reverse () Reverses the order of all elements in S
S.sort ([key [, reverse]]) Sorts all the elements in S. Key is a key function. Reverse indicates that the list is sorted in reverse order

List (s) can convert any of the iteration types to a list. If S is already a list, then the new list constructed by the function is a shallow copy of S.
The following table is the supported methods for strings:

Method Description
S.captitalize () Capitalize the first character
S.center (width [, pad]) Centers the string inside a field with a width of length. Pad is a fill character
S.count (Sub [, Start [, end]]) Calculates occurrences of a sub of a specified substring
S.decode ([encoding [, errors]]) Decodes a string and returns a Unicode string
S.encdoe ([encoding [, errors]]) Returns the encoded version of a string
S.endswith (suffix [, start [, end]]) Checks if the string ends with suffix
S.expandtabs ([tabsize]) Replace tabs with spaces
S.find (Sub [, Start [, end]]) Finds the position of the first occurrence of the specified substring sub, otherwise returns-1
S.format (args, *Kwargs) Formatting s
S.index (Sub [, Start [, end]]) Refers to the position of the first occurrence of the specified substring sub, or an error
S.isalnum () Checks if all characters are letters or numbers
S.isalpha () Checks if all characters are alphabetic
S.isdigit () Checks if all characters are numeric
S.islower () Checks if all characters are lowercase
S.isspace () Checks if all characters are blank
S.istitle () Check if the string is a header string (capitalize each word)
S.isupper () Checks if all characters are uppercase
S.join (t) Use S as a delimiter to concatenate strings in a sequence T
S.ljust (width [, fill]) Left-aligned within a string of length width
S.lower () Convert to lowercase
S.lstrip ([chrs]) Delete the blanks or characters in front of chrs
S.partition (Sep) Use the delimiter string Sep to divide a string. Returns a tuple (head, Sep, tail)
S.replace (old, new [, Maxreplace]) Replace a substring
S.rfind (Sub [, Start [, end]]) Find where a substring last occurred
S.rindex (Sub [, Start [, end]]) Find the last occurrence of a substring, or an error
S.rjust (width [, fill]) Right-aligned within a string of length width
S.rpartition (Sep) Use the delimiter Sep to divide the string, but start the search at the end of the string
S.rsplit ([Sep [, Maxsplit]]) Use Sep as a delimiter to divide a string from back to forward. Maxsplit is the maximum number of partitions
S.rstrip ([chrs]) Delete chrs trailing blanks or characters
S.split ([Sep [, Maxsplit]]) Use Sep as a delimiter to divide a string. Maxsplit is the maximum number of partitions
S.splitlines ([keepends]) Divides a string into a list of rows and columns. If Keepends is 1, the last line break of each row is preserved
S.startswith (prefix [, start [, end]]) Checks whether a string starts with prefix
S.strip ([chrs]) Remove whitespace or characters from the beginning and end of chrs
S.swapcase () Convert uppercase to lowercase, or vice versa
S.title () Convert a string to a header format
S.translate (table [, Deletechars]) Use a character conversion table to convert a string to remove characters from Deletechars
S.upper () Converts a string to uppercase
S.zfill (width) Padding 0 to the left of the string until it is width wide

Many string methods accept the optional start and end parameters, whose value is an integer that specifies the index of the start and end positions in S. In most cases, these values can be negative, indicating that the index starts at the end of the string.
A map type represents a collection of arbitrary objects and can be indexed by another collection that is almost any key value. Unlike sequences, mapping objects are unordered and can be indexed by numbers, strings, and other objects. The mappings are mutable.
A dictionary is the only built-in mapping type, and any immutable object can be used as a dictionary key value, such as a string, a number, a tuple, and so on. The following table is the dictionary method:

Project Description
Len (M) Returns the number of items in M
M[K] Returns the key of the M medium key K
M[K] = X Set the value of M[k] to X
Del M[k] Remove M[k from M]
K in M Returns True if K is a key in M
M.clear () Delete all items in M
M.copy () Returns a copy of M
M.fromkeys (s [, value]) Creates a new dictionary and takes all of the elements in the sequence s as keys to the new dictionary, with values of these keys as value
M.get (k [, V]) Return m[k], if M[K] is not found, then return V
M.items () Returns a sequence consisting of (key, value) pairs
M.keys () Returns a sequence that consists of a key value
M.pop (k [, default]) If M[K] is found, return m[k] and remove from M, otherwise return the value of default
M.popitem () Removes a random (key, value) pair from M and returns it as a tuple
M.setdefault (k [, V]) If M[K] is found, return m[k], do not return V, and set the value of m[k] to V
M.update (b) Add all objects in B to M
M.values () Returns a sequence of all values in M

A collection is the only unordered set. Unlike sequences, collections do not provide an index or slice operation. They also differ from dictionaries in that the object does not have a related key value. The items that are put into the collection must be immutable. A collection is divided into two types, set is a mutable collection, and Frozenset is an immutable collection, both of which are created with a pair of built-in functions, such as:

s = set([1, 5, 10, 15])f = frozenset([‘a‘, 37, ‘hello‘])

The following tables are supported for all collections:

Project Description
Len (s) Returns the number of items in s
S.copy () Make a copy of S
S.difference (t) Differential set. Returns all items that are in the s but not in t
S.intersection (t) To find the intersection. Return all items in both S and T
S.isdisjoint (t) Returns true if S and t do not have the same item
S.issubset (t) Returns true if S is a subset of T
S.issuperset (t) Returns true if S is a superset of T
S.symmetric_difference (t) To find the symmetric difference set. Returns all items in S or T, but not both in both collections
S.union (t) The set of the request. Returns all items in S or T

The Mutable collection also provides some additional methods, such as the following table:

Project Description
S.add (item) Add item to S. If item is already in S, it has no effect
S.clear () Delete all items in S
S.difference_update (t) Remove all items from S that are also in t
S.discard (item) Remove item from S, if item does not have a member of S, then no effect
S.intersection_update (t) Computes the intersection of S with T and puts the result in s
S.pop () Returns an arbitrary collection element and removes it from S
S.remove (item) Remove item from S if item is not a member of S, throws an exception
S.symmetric_difference_update (t) Calculates the symmetric difference between s and T, and puts the result in s
S.update (t) Add all items in T to S

All of these operations can modify the collection s directly.

6. A built-in type that represents a program structure

In Python, functions, classes, and modules are objects that can be manipulated as data, such as the following table:

Type Classification type name Description
Can call Types. Builtinfunctiontype Built-in functions or methods
Can call Type Types of built-in types and classes
Can call Object Ancestors of all types and classes
Can call Types. Functiontype User-defined Functions
Can call Types. Methodtype Class method
Module Types. Moduletype Module
Class Object Ancestors of all types and classes
Type Type Types of built-in types and classes

A callable type represents an object that supports the operation of a function call. Objects with this property are: User-defined functions, methods, built-in functions and methods, callable classes and instances.
A user-defined function is a callable object created at the module level with a DEF statement or lambda operator, which has the following properties:

Properties Description
F._doc_ Document string
F._name_ Function name
F._dict_ A dictionary containing function properties
F._Code_ Code for byte compilation
F._Defaults_ Tuples that contain default parameters
F._Globals_ Define a dictionary of global namespaces
F._closure_ Tuples containing data related to nested scopes

A method is a function that is defined in a class definition. There are 3 common methods: instance methods, class methods, and static methods. An instance method is a method that operates an instance of a specified class, which is passed to the method as the first argument, which is generally called self, according to the Convention. The class method operates on the class itself as an object, passing the class object to the class in the first argument. A static method is a function packaged in a class that cannot use an instance or Class object as the first parameter. For example:

f = Foo()meth = f.instance_methodmeth(30)

In the above example, meth is called a binding method. A binding method is a callable object that encapsulates a function and a related instance. When a binding method is called, the instance is passed to the method as the first argument (self). Method lookups can also occur on the class itself, for example:

umeth = Foo.instance_methodumeth(f, 30)

In the following example, Umeth is called a non-binding method. A non-binding method is a callable object that encapsulates a method function, but it needs to pass an instance of the correct type as the first argument. If the passed object type is wrong, an TypeError exception is thrown.
The following table defines the properties for the method object:

Properties Description
M._doc_ Document string
M._name_ Method name
M._Class_ The class that defines the method
M._func_ The function object that implements the method
M._self_ Method-related instance (none if non-binding method)

class objects and instances can also be manipulated as callable objects. The class object is created using the class statement and is called as a function to create a new instance. In this case, the parameters of the function are passed to the class's _init_() method to initialize the newly created instance. If the instance defines a special method _Call_(), it can simulate the behavior of the function. If the method is defined for an instance x, using the X (args) statement is equivalent to calling the method x._Call_(args).
When defining a class, a class definition typically generates an object of type object, and the common properties of a type objects T are the following table:

Properties Description
T._doc_ Document string
T._name_ Class name
T._Bases_ Tuple of base class
T._dict_ To save a Dictionary of class methods and variables
T._Module_ Define the module name of the class
T._Abstractmethods_ Collection of abstract method names

When you create an object instance, the type of the instance is the class that defines it, for example:

f = Foo()print(type(f)) # <class ‘__main__.Foo‘>

The following table shows the special properties that the instance has:

Properties Description
T._Class_ class to which the instance belongs
T._dict_ Dictionary of Saving instance data

The module type is a container that holds objects that are loaded with the import statement. The module defines a namespace that is implemented using a dictionary, for example, m.x=y equivalent to m._dic_["X"]=y. The available properties of the module are as follows:

Properties Description
M._dict_ Dictionary associated with a module
M._doc_ Module Document String
M._name_ Module name
M._File_ The file used to load the module
M._Path_ Fully qualify the package name, defined only when the module object references the package

[Python] Types and objects

Related Article

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.