Home > Backend Development > Python Tutorial > Summary of basic entry-level operations of Python

Summary of basic entry-level operations of Python

巴扎黑
Release: 2017-08-13 14:53:39
Original
1390 people have browsed it

The following editor will bring you a must-read operation for getting started with Python basics. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Here are the methods and techniques commonly used in developing with python. If there are any mistakes, you are welcome to criticize and correct me.

Key points: Query the characteristics of classes and variables during development, the type is the class, the use of assertions, judgment of dark and shallow copy, etc.

Python script files are encoded using UTF-8, so when Chinese characters are found When garbled characters appear, you should consider whether the text file uses UTF-8 encoding.

If you want to specify different encodings, you need to add such a comment at the beginning of the source code file:


# -*- coding: utf-8 -*-
Copy after login

If python is running in linux and unix systems, You need to add in the first line of the source code:


#!/usr/bin/python3
Copy after login

How to get the contents of each module, variable, class, etc. in python?

Queries about help groups in Python can be obtained through variables __all__, __dict__, functions help(), and dir().

If __all__ is defined in a class or module, it generally contains features that can be called externally. If it is defined without assignment, it will automatically be filled with features that do not start with an underscore. If there is no parameter __all__python will prompt an AttributeError attribute error.

__dict__ generally gives the characteristics (including attributes and methods) defined in the class or module, which are output in the form of a dictionary using tuples to represent parameters and parameter values ​​(parameters, parameter values ​​or descriptions)

List's __dict__ view


>>> list.__dict__
2 mappingproxy({&#39;__repr__&#39;: <slot wrapper &#39;__repr__&#39; of &#39;list&#39; objects>, &#39;__hash__&#39;: None, &#39;__getattribute__&#39;: <slot wrapper &#39;__getattribute__&#39; of &#39;list&#39; objects>, &#39;__lt__&#39;: <slot wrapper &#39;__lt__&#39; of &#39;list&#39; objects>, &#39;__le__&#39;: <slot wrapper &#39;__le__&#39; of &#39;list&#39; objects>, &#39;__eq__&#39;: <slot wrapper &#39;__eq__&#39; of &#39;list&#39; objects>, &#39;__ne__&#39;: <slot wrapper &#39;__ne__&#39; of &#39;list&#39; objects>, &#39;__gt__&#39;: <slot wrapper &#39;__gt__&#39; of &#39;list&#39; objects>, &#39;__ge__&#39;: <slot wrapper &#39;__ge__&#39; of &#39;list&#39; objects>, &#39;__iter__&#39;: <slot wrapper &#39;__iter__&#39; of &#39;list&#39; objects>, &#39;__init__&#39;: <slot wrapper &#39;__init__&#39; of &#39;list&#39; objects>, &#39;__len__&#39;: <slot wrapper &#39;__len__&#39; of &#39;list&#39; objects>, &#39;__getitem__&#39;: <method &#39;__getitem__&#39; of &#39;list&#39; objects>, &#39;__setitem__&#39;: <slot wrapper &#39;__setitem__&#39; of &#39;list&#39; objects>, &#39;__delitem__&#39;: <slot wrapper &#39;__delitem__&#39; of &#39;list&#39; objects>, &#39;__add__&#39;: <slot wrapper &#39;__add__&#39; of &#39;list&#39; objects>, &#39;__mul__&#39;: <slot wrapper &#39;__mul__&#39; of &#39;list&#39; objects>, &#39;__rmul__&#39;: <slot wrapper &#39;__rmul__&#39; of &#39;list&#39; objects>, &#39;__contains__&#39;: <slot wrapper &#39;__contains__&#39; of &#39;list&#39; objects>, &#39;__iadd__&#39;: <slot wrapper &#39;__iadd__&#39; of &#39;list&#39; objects>, &#39;__imul__&#39;: <slot wrapper &#39;__imul__&#39; of &#39;list&#39; objects>, &#39;__new__&#39;: <built-in method __new__ of type object at 0x000000005BBAF530>, &#39;__reversed__&#39;: <method &#39;__reversed__&#39; of &#39;list&#39; objects>, &#39;__sizeof__&#39;: <method &#39;__sizeof__&#39; of &#39;list&#39; objects>, &#39;clear&#39;: <method &#39;clear&#39; of &#39;list&#39; objects>, &#39;copy&#39;: <method &#39;copy&#39; of &#39;list&#39; objects>, &#39;append&#39;: <method &#39;append&#39; of &#39;list&#39; objects>, &#39;insert&#39;: <method &#39;insert&#39; of &#39;list&#39; objects>, &#39;extend&#39;: <method &#39;extend&#39; of &#39;list&#39; objects>, &#39;pop&#39;: <method &#39;pop&#39; of &#39;list&#39; objects>, &#39;remove&#39;: <method &#39;remove&#39; of &#39;list&#39; objects>, &#39;index&#39;: <method &#39;index&#39; of &#39;list&#39; objects>, &#39;count&#39;: <method &#39;count&#39; of &#39;list&#39; objects>, &#39;reverse&#39;: <method &#39;reverse&#39; of &#39;list&#39; objects>, &#39;sort&#39;: <method &#39;sort&#39; of &#39;list&#39; objects>, &#39;__doc__&#39;: "list() -> new empty list\nlist(iterable) -> new list initialized from iterable&#39;s items"})
Copy after login

dir() will give all the available feature attributes in the form of a list, without values ​​and Attribute description:

list uses dir() to view


1 >>> dir(list)
2 [&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__delitem__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__iadd__&#39;, &#39;__imul__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__iter__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__reversed__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__setitem__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;append&#39;, &#39;clear&#39;, &#39;copy&#39;, &#39;count&#39;, &#39;extend&#39;, &#39;index&#39;, &#39;insert&#39;, &#39;pop&#39;, &#39;remove&#39;, &#39;reverse&#39;, &#39;sort&#39;]
Copy after login

Generally speaking, just use __dict__ and dir(). Of course, many times You need help() to view detailed documents (actually the content in __doc__):

list Use help() to view


help(list)
Help on class list in module builtins:

class list(object)
 | list() -> new empty list
 | list(iterable) -> new list initialized from iterable&#39;s items
 |
 | Methods defined here:
 |
 | __add__(self, value, /)
 |  Return self+value.
 |
 | __contains__(self, key, /)
 |  Return key in self.
 |
 | __delitem__(self, key, /)
 |  Delete self[key].
 |
 | __eq__(self, value, /)
 |  Return self==value.
 |
 | __ge__(self, value, /)
 |  Return self>=value.
 |
 | __getattribute__(self, name, /)
 |  Return getattr(self, name).
 |
 | __getitem__(...)
 |  x.__getitem__(y) <==> x[y]
 |
-- More --
Copy after login

If we now An object a = list() is created. Now if you want to get the characteristic methods of object a, you can also use dir() and help().

What needs to be emphasized here is that the power of dir() and help() can not only check the class, but also the variables we define. This way we can get more content during the encoding process.

Search for variable a containing methods in a=1


>>> a=1
>>> dir(a)
[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__bool__&#39;, &#39;__ceil__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__pmod__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__float__&#39;, &#39;__floor__&#39;, &#39;__floorp__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__index__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__le__&#39;, &#39;__lshift__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__or__&#39;, &#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rpmod__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloorp__&#39;, &#39;__rlshift__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__round__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;, &#39;__rsub__&#39;, &#39;__rtruep__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truep__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;, &#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;from_bytes&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;, &#39;to_bytes&#39;]
>>> help(a)
Help on int object:

class int(object)
 | int(x=0) -> integer
 | int(x, base=10) -> integer
 |
 | Convert a number or string to an integer, or return 0 if no arguments
 | are given. If x is a number, return x.__int__(). For floating point
 | numbers, this truncates towards zero.
 |
 | If x is not a number or if base is given, then x must be a string,
 | bytes, or bytearray instance representing an integer literal in the
 | given base. The literal can be preceded by &#39;+&#39; or &#39;-&#39; and be surrounded
 | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
 | Base 0 means to interpret the base from the string as an integer literal.
 | >>> int(&#39;0b100&#39;, base=0)
 | 4
 |
 | Methods defined here:
 |
 | __abs__(self, /)
 |  abs(self)
 |
 | __add__(self, value, /)
 |  Return self+value.
 |
 | __and__(self, value, /)
 |  Return self&value.
 |
-- More --
Copy after login

Search for variables and object types and other operations

In addition to using dir(), help(), __all__, __dict__ to view the content of the original definition design in python, you can use many defined features to obtain more information:

Methods to get variable types and object types:

Query variables and class types through __class__


>>> a =1
>>> a.__class__
<class &#39;int&#39;>
>>> b = 1.0
>>> b.__class__
<class &#39;float&#39;>
>>> c = &#39;&#39;
>>> c.__class__
<class &#39;str&#39;>
>>> d = list()
>>> d.__class__
<class &#39;list&#39;>
>>> e = tuple()
>>> e.__class__
<class &#39;tuple&#39;>
>>> f = dict()
>>> f.__class__
<class &#39;dict&#39;>
>>> list.__class__
<class &#39;type&#39;>
>>> dict.__class__
<class &#39;type&#39;>
>>> tuple.__class__
<class &#39;type&#39;>
>>> object.__class__
<class &#39;type&#39;>
>>> None.__class__
<class &#39;NoneType&#39;>
Copy after login

Through the above code we find that if class For type, in fact, this itself is the definition of a class, if it is something else, it is an object.

Have you ever thought that basic variables in python are also objects?

In general languages, our types are divided into integers, floating point types, strings, etc. But in Python these types are actually defined in the form of classes, and classes also inherit top-level superclasses.

Use __class__ to view the type and __bases__ to view the super class


>>> a = 1
>>> a.__class__
<class &#39;int&#39;>
>>> int.__class__
<class &#39;type&#39;>
>>> str.__class__
<class &#39;type&#39;>
>>> bool.__class__
<class &#39;type&#39;>
>>> list.__class__
<class &#39;type&#39;>
>>> dict.__class__
<class &#39;type&#39;>
>>> tuple.__class__
<class &#39;type&#39;>
>>> type.__class__
<class &#39;type&#39;>
>>> object.__class__
<class &#39;type&#39;>
>>> type.__bases__
(<class &#39;object&#39;>,)
>>> int.__bases__
(<class &#39;object&#39;>,)
>>> str.__bases__
(<class &#39;object&#39;>,)
>>> bool.__bases__
(<class &#39;int&#39;>,)
>>> float.__bases__
(<class &#39;object&#39;>,)
>>> object.__bases__
()
>>>
Copy after login

I found out that no, the types we use are actually classes, except bool which inherits Class int, others inherit the super class object. The object class has no superclass. It should be said that type is a type class! Of course, the None type is NoneType, but NoneType is not a class. This means that None is a null value.

The content contained in the type class and the content contained in the object class


>>> dir(type)
[&#39;__abstractmethods__&#39;, &#39;__base__&#39;, &#39;__bases__&#39;, &#39;__basicsize__&#39;, &#39;__call__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dict__&#39;, &#39;__dictoffset__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__flags__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__instancecheck__&#39;, &#39;__itemsize__&#39;, &#39;__le__&#39;, &#39;__lt__&#39;, &#39;__module__&#39;, &#39;__mro__&#39;, &#39;__name__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__prepare__&#39;, &#39;__qualname__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasscheck__&#39;, &#39;__subclasses__&#39;, &#39;__subclasshook__&#39;, &#39;__text_signature__&#39;, &#39;__weakrefoffset__&#39;, &#39;mro&#39;]
>>> dir(object)
[&#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__le__&#39;, &#39;__lt__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;]
Copy after login

is and id() allow us to see Clear the hidden relationships between variables!

We all know that python has the convenience of weak types in use. Of course, in python, there is only one variable with the same value! Why is this? This is because they all point to the same memory address. You can think of these variables as storing memory addresses one by one. Our assignment to them is just changing the memory addresses they point to! !

It is helpful to understand python from the perspective of pointers. The variable itself stores pointers. If you can understand this, then you can easily understand and use Python's variables and memory recycling mechanism.

A is B The function of the operation is to determine whether A is B. If it is true, it means that A and B are the same object. If it is false, it means that A and B are not the same object.

id(A) The function of the operation is to determine the id sequence number of A in the memory.

Let’s explain in detail the related phenomena in python:

1. Although A and B in python are the same Object, but after assigning a value to A, A and B are the same object again, because the assignment in python changes the address pointed by A to the address of another object, which is different from the address in B. The value of the object caused by the B address will not be affected by the A assignment.

2.python中同一个对象所具有的id可能是不同的,因为在没有指向该地址的变量时,python内存自动清理会清理掉这个对象。再次使用到具有相同数值的对象可能是在前一个对象自动清理之后创建的新对象。

针对第一个情况我们首先通过对True和False和数字来确定哪些值对象的id是系统自带的,即便这些值对象不被变量使用python内存清理也不会清理这些对象!

通过id来判断数值和布尔值中的值对象是否是系统自带的对象


>>> id(True)
1538937056
>>> id(False)
1538937088
>>> id(False) - id(True)
32
>>> id(-5)
1539416992
>>> id(-6)
1667933956912
>>> id(-4)
1539417024
>>> id(-4)-id(-5)
32
>>> id(-3)-id(-4)
32
>>> id(-3)
1539417056
>>> id(-2)
1539417088
>>> id(-2) - id(-3)
32
>>> id(255)
1539425312
>>> id(256)
1539425344
>>> id(256) - id(255)
32
>>> id(257)
1667904611440
>>> id(1.0)
1667904643192
Copy after login

你会发现数字-5到256是连续的,他们相邻的id值相差是32,意思是他们是32表示的数值。id返回的值就是他们在python中逻辑内存地址的值,在不同python进程中这些相同值对象返回的id值是一致的。而小于-5或者大于256的数值,小数,超过单个字符的字符串都是python在用户使用时创建的值对象,在不同的python进程中相同的值的id是不同的!其他值在不使用时有的就会被python内存清理程序清理掉释放内存!

当然,python中还有很多对象、类、函数等是python自创建的不会因为不使用而被内存清理程序清理掉。比如 int,None,dict,list。

不够值得一提的是 None is None是返回True 。并且id(None)的返回值是1538983120。这说明与其他脚本(比如javascript)不一样,None是空值,是一个唯一的空值对象,程序中所有的None都是相等的。都是同一个内存地址中存放的值。

很多情况下,我们想判断两个变量是否指向同一个内存地址块存放的值,可以使用is来判断。

python中对于全局变量,局部变量,外部变量有着额外的处理方式

如果一个函数中定义了与外部名称相同的变量,在函数内部如何能够获得外部定义的变量呢?在其他语言中,我们都知道局部变量会覆盖掉同名的外部变量。而在python中虽然也是这个逻辑,但是他提供了 3个函数来使得我们能够获得不同作用域中定义的同名的变量值。

globals()获取所有全局变量值

locals()获取所有局部变量值

nonlocals()获取所有外部变量值(因为python是支持函数嵌套的,内部函数如果想要获得外部函数局部变量的值可以使用这个)

在局部变量中获取全局变量中同名变量


>>> a = 234
>>> globals()
{&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <class &#39;_frozen_importlib.BuiltinImporter&#39;>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;a&#39;: 234}
>>> def s():
...  a = &#39;hello&#39;
...  print(locals())
...
>>> s()
{&#39;a&#39;: &#39;hello&#39;}
>>> def u():
...  a = &#39;world&#39;
...  c = globals()[&#39;a&#39;]
...  print(c)
...
>>> u()
234
Copy after login

如上面代码显示的,在函数u()中a的值是‘world'而在全局变量中a的值是234,函数s()中局部变量a的值是'hello'通过globals()[变量名]就可以获得全局变量中同名的变量的值。

局部改变上段代码中同名的全局变量值


>>> def e():
...  a = &#39;sdf&#39;
...  globals()[&#39;a&#39;] = a
...
>>> e()
>>> a
&#39;sdf&#39;
>>>
Copy after login

The above is the detailed content of Summary of basic entry-level operations of Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template