Python basic functions 06 (S ~ Z)

The Python interpreter has many built-in functions and types that are always available. They are listed here in alphabetical order.

Built-in Functions Built-in Functions
set() setattr()
slice() sorted()
staticmethod() str()
sum() super()
tuple() type()
whose() zip()

class set([iterable])

Returns a new set object, optionally using elements from iterable. set is a built-in class. For documentation of this type, see set and set types—set and frozenset.
For other containers, you can view the built-in frozenset, list, tuple, and dict classes, and the collections module.

setattr(object, name, value)

This is a copy of getattr (). The parameter is an object, a string, and an arbitrary value. Strings can name existing attributes or new attributes. If the object allows it, the function assigns the value to the property. For example, setattr (x, 'foobar', 123) is equal to x. foobar = 123.

class slice(stop)

class slice(start, stop[, step])

Returns a slice object, which represents a set of indexes specified by the range (start, stop, step). The start and step parameters default to None. The Slice object has read-only data attributes start, stop, and step, which only return the parameter value (or its default value). They have no other explicit functions; but they are used by Numerical Python and other third-party extensions. When using the extended index syntax, Slice objects are also generated. For example: a [start: stop: step] or a [start: stop, i]. See itertools.islice () for alternative versions of returning iterators.

sorted(iterable, *, key=None, reverse=False)

Return a new sorted list from the items in iterable.

There are two optional parameters, which must be specified as keyword parameters.

key specifies a parameter function that is used to extract a comparison key from each element in the iterable (for example, key = str.lower). The default value is None (compare elements directly).

reverse is a Boolean value. If set to True, the list elements will be sorted in the order of each comparison.

Use functools.cmp_to_key () to convert old-style cmp functions to key functions.

The built-in sort () function is guaranteed to be stable. Sorting is stable if it is guaranteed not to change the relative order of elements that are equal—this helps sorting among multiple passes (for example, sorting by department and then by salary grade)

For sorting examples and short sorting tutorials, see How to Sort.

@staticmethod

Convert the method to a static method.

Static methods do not receive the implicit first parameter. To declare a static method, use the following idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@staticmethod form is a function decorator-see function definition for details.

Static methods can be called on a class (such as Cf ()) or on an instance (such as C (). F ()).

Static methods in Python are similar to methods in Java or C ++. See also classmethod () for variables used to create alternative class constructors.

Like all decorators, you can also call staticmethod as a regular function and process its results. In some cases, you need to reference a function from the class body, and you want to avoid automatic conversion to instance methods, you need to do this. For these situations, you can use this idiom:

class C:
    builtin_open = staticmethod(open)
For more information on static methods, see The standard type hierarchy.

class str(object=’ ')

class str(object=b’’, encoding=‘utf-8’, errors=‘strict’)

Return a str version of the object. For more information, see str ().

str is a built-in string class. For general information about character strings, see Text Sequence Type-str.

sum(iterable, /, start=0)

And start, iterate the items from left to right, and return the total. Iterable items are usually numbers, and the starting value is not allowed to be a string.

For some use cases, sum () has a good alternative. The preferred quick way to connect string sequences is to call ".join (sequence)". To add floating-point values ​​with extended precision, see math.fsum (). To connect a series of iterators, consider using itertools.chain ().

Changed in version 3.8: The start parameter can be specified as a keyword parameter.

super([type[, object-or-type]])

Returns a proxy object that delegates method calls to the parent or sibling of the type. This is very useful for accessing inherited methods that are overridden in the class.

The object or type determines the resolution order of the methods to be searched. The search starts with the class behind the type.

For example, if _mro__ of object-or-type is D-> B → C → an → object, and the value of type is B, then super () searches for C-> an → object.

The _mro__ attribute of object-or-type lists the method used by getattr () and super () to resolve the search order. Attributes are dynamic and can be changed when the inheritance hierarchy is updated.

If the second parameter is omitted, the returned superobject will be unbound. If the second parameter is an object, isinstance (obj, type) must be true. If the second parameter is a type, then issubclass (type2, type) must be true (this is useful for class methods).
There are two typical use cases for super. In the class hierarchy of single inheritance, you can use super to refer to the parent class without having to explicitly name them, making the code easier to maintain. This usage is very similar to the usage of super in other programming languages.

The second use case is to support collaborative multiple inheritance in a dynamic execution environment. This use case is unique to Python and cannot be found in statically compiled languages ​​or languages ​​that only support single inheritance. This makes it possible to implement "diamond graphs" in which multiple base classes implement the same method. Good design requires that this method has the same call signature in every case (because the order of the calls is determined at runtime, because the order adapts to changes in the class hierarchy, and the order can contain sibling classes that were unknown before runtime ).

For these two use cases, a typical superclass call looks like this:

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

In addition to method search, super () can also be used for attribute search. One possible use case is to call descriptors in parent or sibling classes.

Note that super () is implemented as part of the binding process for explicit dotted attribute lookups (such as super () ._ getitem __ (name)). It does this by implementing its own _getattribute __ () method, which is used to search for classes in a predictable order that supports collaborative multiple inheritance. Therefore, for implicit search using operators such as statements or super () [name], super () is undefined.

Also note that except for the zero parameter form, super () is not limited to use within methods. These two parameter forms specify the parameters precisely and provide appropriate references. The zero parameter form only works in the class definition, because the compiler will fill in the necessary details to correctly retrieve the class being defined and access the current instance of the ordinary method.

For practical advice on how to use super () to design collaboration classes, please refer to the guide on using super ().

class tuple([iterable])

Tuple is not a function, it is actually an immutable sequence type, as documented in tuples and sequence types (list, tuple, range).

class type(object)

class type(name, bases, dict)

Use one parameter to return the type of object. The return value is a type object, usually the same as the object returned by object._class__.

It is recommended to use the isinstance () built-in function to test the type of object because it takes into account subclasses.

With three parameters, return a new type object. This is essentially a dynamic form of class statements. The name string is the class name and becomes the _name__ attribute; the primitive group lists the base classes item by item and becomes the _bases__ attribute; the dict dictionary is the namespace containing the definition of the class body, which is copied into a standard dictionary Become a _dict__ attribute. For example, the following two statements create objects of the same type:

```handlebars
class X:
    a = 1

X = type('X', (object,), dict(a=1))
See also Type Objects.

Changed in version 3.6: Subclasses of type which don’t override type.new may no longer use the one-argument form to get the type of an object.

vars([object])

Returns the attributes of the __dict__ module, class, instance, or any other object with the __dict__ attribute.

Objects (such as modules and instances) have updatable __dict__ attributes. However, other objects may have write restrictions on their __dict__ attributes (for example, classes use types.MappingProxyType to prevent direct dictionary updates).

Without argument, vars () is like locals (). Please note that local dictionaries are only useful for reading, because updates to local dictionaries will be ignored.

zip(*iterables)

Make an iterator that aggregates the elements in each iterable object.

Returns an iterator of tuples, where the i-th tuple contains the i-th element in each parameter sequence or iterable object. When the shortest iterable input is exhausted, the iterator stops. With a single iterable parameter, it will return a 1-tuple iterator. Without parameters, it will return an empty iterator. Equivalent to:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

The order of evaluation of the iterable objects from left to right is guaranteed. This makes the usage of zip (* [iter (s)] * n) a cluster that can cluster data series into n lengths. This will repeat the same iterator n times, so that each output tuple has the result of n calling the iterator. This has the effect of dividing the input into n length blocks.

zip () should only be used with unequal length input if you don't care about the trailing, unmatched value of a longer iterable. If these values ​​are important, please use itertools.zip_longest () instead.

zip () can be used with the * operator to decompress lists:

>>>
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
Published 36 original articles · praised 0 · visits 619

Guess you like

Origin blog.csdn.net/Corollary/article/details/105424912