首頁 > web前端 > js教程 > 主體

全端開發:作為 JavaScript 開發人員學習 Python

WBOY
發布: 2024-08-31 00:22:33
原創
509 人瀏覽過

Fullstack Development: Learning Python as JavaScript Developers

旅程開始

我作為前端開發人員已經工作了 8 年多,在過去的 2 年裡,我決定重新思考我的職業生涯以及如何成長。我發現前端技術變化頻繁:不同的框架、概念以及React類別元件和鉤子之間的差距。我意識到這一切只是用來表達業務需求和個人願景的抽象。從那時起,我決定​​改變自己的職涯道路,稍微成為全端開發人員。

眾所周知,現在的前端開發都是JavaScript,這也是我決定學習Node.js及其主要框架的原因。所有前端開發人員都會以某種方式遇到 Node.js,身為高階前端開發人員,您應該能夠使用 Express 或其他函式庫在 Node.js 中編寫基本端點。經過兩年在 Node.js 方面的積極開發,當我的工作在前端和後端之間達到 50/50 時,我發現大多數專案並不局限於一種語言。

Node.js 並不是萬能的理想工具,尤其是當您在一家較大的公司工作時。不同的語言提供不同的解決方案或更適合解決特定的業務案例。這就是為什麼我開始研究我可以學習什麼作為我的第二後端語言以及我將來如何利用它。

我想分享我的經驗以及為什麼我在嘗試學習 Rust(主要不是用於 Web 開發)、Swift(主要是行動優先解決方案)和 Golang 後決定堅持使用 Python。在這裡,您將了解為什麼我相信 Python 是前端開發人員學習以及如何開始使用它的絕佳機會。

為什麼選擇Python?

如今,人工智慧是每個人都在談論的話題。在採訪中提及它作為你的經歷的一部分總是會給你加分。幾乎所有公司都在嘗試將人工智慧融入他們的產品中,而Python與人工智慧和機器學習並進。透過學習 Python,您不僅有機會使用 Django、Flask 和 FastAPI 等框架編寫 Web 應用程序,還可以開始使用機器學習和 AI 服務。
一方面,如果你想成為更好的程式設計師,學習 Rust、Go 或 Elixir 等更複雜的語言是個好主意。然而,從職業角度來看,要成為一名使用自己不太熟悉的完全不同語言的後端開發人員並不是一件容易的事。

Python 是一種動態型別程式語言。作為一個在類似環境中度過了職業生涯的大部分時間的 JavaScript 開發人員,這不應該讓您感到害怕,因為您已經知道程式碼中會出現哪些類型的問題。
使用Python,您不僅可以開始編寫Web應用程序,還可以利用您在AI相關領域的技能,這使Python作為第二語言具有顯著的優勢。

學習曲線

學習曲線很簡單。在Python中,你絕對需要學習一些基本概念。如果您有 JavaScript 經驗,那應該不是什麼大問題。

以下是 Python 程式碼範例:

import random

def guess_the_number():
    number_to_guess = random.randint(1, 100)
    attempts = 0
    guessed = False

    print("Welcome to the Number Guessing Game!")
    print("I'm thinking of a number between 1 and 100. Can you guess what it is?")

    while not guessed:
        user_guess = int(input("Enter your guess: "))
        attempts += 1

        if user_guess < number_to_guess:
            print("Too low! Try again.")
        elif user_guess > number_to_guess:
            print("Too high! Try again.")
        else:
            print(f"Congratulations! You guessed the number {number_to_guess} in {attempts} attempts.")
            guessed = True

guess_the_number()
登入後複製

我認為你不會在這裡發現任何太複雜的東西。即使你之前沒有學過Python,你也可以在不閱讀文件的情況下理解幾乎所有的行。

您會注意到的最大區別是 Python 使用縮進來定義程式碼區塊而不是花括號。這可能看起來很奇怪,我仍然覺得它有點不尋常,但過了一段時間,你就會習慣它,閱讀程式碼變得更容易。

除此之外,Python 中的許多概念與 JavaScript 中的相似。您可以使用 print 來代替 console.log,對於字串插值,您可以在字串的開頭添加 f 並使用與 JavaScript 中幾乎相同的語法。

這是上面程式碼的 JavaScript 版本:

function guessTheNumber() {
    const numberToGuess = Math.floor(Math.random() * 100) + 1;
    let attempts = 0;
    let guessed = false;

    console.log("Welcome to the Number Guessing Game!");
    console.log("I'm thinking of a number between 1 and 100. Can you guess what it is?");

    while (!guessed) {
        const userGuess = parseInt(prompt("Enter your guess: "), 10);
        attempts++;

        if (userGuess < numberToGuess) {
            console.log("Too low! Try again.");
        } else if (userGuess > numberToGuess) {
            console.log("Too high! Try again.");
        } else {
            console.log(`Congratulations! You guessed the number ${numberToGuess} in ${attempts} attempts.`);
            guessed = true;
        }
    }
}

guessTheNumber();
登入後複製

克服障礙:關鍵概念

你可以在Python中學習很多不同的概念。身為 JavaScript 開發者,我展示了最令人困惑的部分。

基於縮排的語法

身為 JavaScript 開發人員,您可能熟悉如何使用帶有 if/else 和其他運算子的程式碼區塊。在大多數情況下,您只需添加 {} 即可。 Python 基於縮排的系統可能很棘手。

讓我們來看看 JavaScript 程式碼:

if (role === "admin") {
    const posts = getDraftPosts()

    if (posts.length === 0) {
        throw NotFound()
    }   

    return posts
}
登入後複製

Python 模擬:

if role == "admin":
    posts = get_draft_posts()

    if posts.length == 0:
        raise NotFound()

    return posts
登入後複製

As you can see readability of blocks in Python could be challenging from the first view. This is why for me it was important to avoid deeply nested blocks because it is hard to read and easy to miss correct indention. Keep in mind that Python could attach your code to a wrong code block because of missed indention.

Type system

Python is a dynamic typing language but I was surprised to find Python built-in Types annotation.

def add(x: int, y: int) -> int:
    return x + y
登入後複製

You don’t need to install additional features, only what you need in Python *3.5 and above.*

Even more complex types could be described as equal to Typescript:

# enums
from enum import Enum # import enum for built in lib

class Season(Enum): # extend class to mark it as enum
    SPRING = 1
    SUMMER = 2
    AUTUMN = 3
    WINTER = 4

print(Season.SPRING.name) # SPRING
print(Season.SPRING.value) # 1

# or generics
def first(container: List[T]) -> T:
    return container[0]

list_two: List[int] = [1, 2, 3]
print(first(list_two)) # 1
登入後複製

For using these types you are not required to install something or transpile this code. This is something I missed in JavaScript, at least Node.js. I know Node.js is adding some basic types in the nearest version (see Medium post about node.js built-in types support) but it looks poor now if you compare it with Python.

Python’s Global Interpreter Lock (GIL)

JavaScript uses an event-driven, non-blocking model, while Python's Global Interpreter Lock (GIL) can be a confusing concept in multi-threaded programs.
The Python Global Interpreter Lock (GIL) is a mechanism that ensures only one thread executes Python code at a time. Even if your Python program has multiple threads, only one thread can execute Python code at a time due to the GIL.
With JavaScript, you can achieve multithreading with web workers, but in Python, you need to use additional libraries to accomplish this.

A Pythonic Mindset

JavaScript's "multiple ways to do it" philosophy doesn't work as well in Python because Python adheres more closely to the concept "There should be one - and preferably only one - obvious way to do it."
In the JavaScript world, every company often creates its own code style guide, and it's fortunate if it follows basic JavaScript style recommendations. In reality, practices like using semicolons can vary widely, to the point where one project might use semicolons and another might not.
In Python, following Pythonic principles from PEP 8 (Python's style guide) is highly recommended. This guide outlines the basic rules of how to write Python code.
To write better code, it's essential to engage with the community and learn idiomatic Python practices that prioritize clarity and simplicity.

Managing Dependencies and Virtual Environments

This part might also be confusing. In JavaScript, you can usually add a package manager and start installing dependencies without any issues. However, Python’s pip and virtual environments may be new concepts.

In Python, when using additional dependencies, it’s highly recommended to use a separate virtual environment. Installing dependencies with pip (the Python equivalent of npm in JavaScript) in your environment could potentially break system utilities or the OS itself, as the system Python interpreter (the one that comes pre-installed with your operating system) is used by the OS and other system utilities.

As a solution, you can create a virtual environment with venv module:

python -m venv myenv
myenv\Scripts\activate # for windows
source myenv/bin/activate # for Mac
登入後複製

After you enter the virtual environment you can install all dependencies without any problem or danger for your root environment.

Finding Support and Resources

How I Learned Python

Learning a new language is always challenging. I started learning Python basics on an online platform, where I also completed some small projects. Here is the plan I used during my learning process:

  • Python basics.
  • Advanced Python concepts (module system, types, environment, async code).
  • Learning the basics of the most popular frameworks like Django, Flask, and FastAPI.
  • Writing my first API server with FastAPI.
  • Adding a database and learning how to work with databases in Python.
  • Deploying the application on a free hosting service.

Where to Find Help

You can find a lot of help in Reddit communities or Discord servers while learning. I’m mostly a Reddit user and would suggest finding subreddits for Python and the framework you decide to use for your first application.

Remember to use the official documentation. In my opinion, it looks overwhelming, and most of the time, I try to find related articles if I get stuck on a concept.

Make sure to read PEP 8 — Style Guide for Python Code, where you can find basic rules on how to write Python code.

回顧與展望

當我回顧自己從 JavaScript 開發人員到擁抱 Python 的旅程時,我並不後悔。這一轉變帶來了令人興奮的機會,特別是在人工智慧和機器學習領域,我現在在我的專案中廣泛利用這些機會,尤其是在後端。

展望未來,Python 的可能性是巨大的。無論是 Web 開發、資料科學、自動化,或是深入研究人工智慧和機器學習,Python 都提供了強大且多功能的基礎來建立和探索新視野。

以上是全端開發:作為 JavaScript 開發人員學習 Python的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板