Heim > Web-Frontend > js-Tutorial > Hauptteil

Fullstack-Entwicklung: Python als JavaScript-Entwickler lernen

WBOY
Freigeben: 2024-08-31 00:22:33
Original
376 Leute haben es durchsucht

Fullstack Development: Learning Python as JavaScript Developers

Die Reise beginnt

Ich arbeite seit mehr als 8 Jahren als Frontend-Entwickler und habe in den letzten 2 Jahren beschlossen, meine Karriere und meine Weiterentwicklung zu überdenken. Ich habe festgestellt, dass sich die Frontend-Technologie häufig ändert: unterschiedliche Frameworks, Konzepte und die Lücke zwischen Komponenten und Hooks der React-Klasse. Mir wurde klar, dass dies alles nur eine Abstraktion ist, die dazu dient, geschäftliche Bedürfnisse und persönliche Visionen auszudrücken. Von diesem Zeitpunkt an beschloss ich, meinen Karriereweg zu ändern und ein wenig zum Full-Stack-Entwickler zu werden.

Wie wir alle wissen, dreht sich bei der Frontend-Entwicklung heutzutage alles um JavaScript, weshalb ich mich entschieden habe, Node.js und seine wichtigsten Frameworks zu lernen. Alle Frontend-Entwickler begegnen Node.js auf die eine oder andere Weise, und als Senior Frontend Developer sollten Sie in der Lage sein, grundlegende Endpunkte in Node.js mit Express oder einer anderen Bibliothek zu schreiben. Nach zwei Jahren aktiver Entwicklung auf der Node.js-Seite, als mein Job 50/50 zwischen Frontend und Backend wurde, stellte ich fest, dass sich die meisten Projekte nicht auf nur eine Sprache beschränken.

Node.js ist nicht für alles das ideale Tool, insbesondere wenn Sie in einem größeren Unternehmen arbeiten. Unterschiedliche Sprachen bieten unterschiedliche Lösungen oder sind optimaler für die Lösung spezifischer Geschäftsfälle. Aus diesem Grund begann ich zu recherchieren, was ich als meine zweite Backend-Sprache lernen und wie ich sie in Zukunft nutzen könnte.

Ich möchte meine Erfahrungen teilen und warum ich mich entschieden habe, bei Python zu bleiben, nachdem ich versucht habe, Rust (hauptsächlich nicht für die Webentwicklung), Swift (das in erster Linie eine Mobile-First-Lösung ist) und Golang zu lernen. Hier erfahren Sie, warum ich glaube, dass Python eine großartige Gelegenheit für Frontend-Entwickler ist, es zu lernen und wie man damit beginnt.

Warum Python?

Heutzutage ist KI in aller Munde. Wenn Sie es in einem Vorstellungsgespräch als Teil Ihrer Erfahrung erwähnen, erhalten Sie immer zusätzliche Punkte. Fast alle Unternehmen versuchen, KI in ihre Produkte zu integrieren, und Python geht Hand in Hand mit KI und maschinellem Lernen. Durch das Erlernen von Python erhalten Sie nicht nur die Möglichkeit, Webanwendungen mit Frameworks wie Django, Flask und FastAPI zu schreiben, sondern können auch mit maschinellem Lernen und KI-Diensten arbeiten.
Einerseits ist das Erlernen komplexerer Sprachen wie Rust, Go oder Elixir eine gute Idee, wenn Sie ein besserer Programmierer werden möchten. Aus beruflicher Sicht ist es jedoch kein einfacher Übergang zum Backend-Entwickler mit einer völlig anderen Sprache, mit der Sie weniger vertraut sind.

Python ist eine dynamisch typisierte Programmiersprache. Als JavaScript-Entwickler, der einen erheblichen Teil Ihrer Karriere in einer ähnlichen Umgebung verbracht hat, sollte Sie das nicht einschüchtern, da Sie bereits wissen, welche Art von Problemen im Code zu erwarten sind.
Mit Python können Sie nicht nur mit dem Schreiben von Webanwendungen beginnen, sondern auch Ihre Fähigkeiten in KI-bezogenen Bereichen nutzen, was Python als Zweitsprache einen erheblichen Vorteil verschafft.

Die Lernkurve

Die Lernkurve war unkompliziert. In Python müssen Sie auf jeden Fall einige grundlegende Konzepte erlernen. Wenn Sie Erfahrung mit JavaScript haben, sollte das keine große Sache sein.

Hier ist das Codebeispiel in 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()
Nach dem Login kopieren

Ich glaube nicht, dass Sie hier etwas zu Komplexes finden werden. Auch wenn Sie Python noch nie gelernt haben, können Sie fast alle Zeilen verstehen, ohne die Dokumentation zu lesen.

Der größte Unterschied, den Sie bemerken werden, besteht darin, dass Python zur Definition von Codeblöcken Einrückungen anstelle von geschweiften Klammern verwendet. Das mag seltsam erscheinen und ich finde es immer noch etwas ungewöhnlich, aber nach einer Weile gewöhnt man sich daran und das Lesen von Code wird einfacher.

Abgesehen davon ähneln viele Konzepte in Python denen in JavaScript. Anstelle von console.log können Sie print verwenden und für die String-Interpolation können Sie f am Anfang des Strings hinzufügen und fast die gleiche Syntax wie in JavaScript verwenden.

Hier ist die JavaScript-Version des obigen Codes:

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();
Nach dem Login kopieren

Hindernisse überwinden: Schlüsselkonzepte

Sie können viele verschiedene Konzepte in Python lernen. Ich habe das für mich als JavaScript-Entwickler am verwirrendste dargestellt.

Einrückungsbasierte Syntax

Als JavaScript-Entwickler sind Sie möglicherweise mit der Verwendung von Codeblöcken mit if/else und anderen Operatoren vertraut. In den meisten Fällen fügen Sie einfach {} hinzu und das war’s. Das einrückungsbasierte System von Python kann schwierig sein.

Sehen wir uns den JavaScript-Code an:

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

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

    return posts
}
Nach dem Login kopieren

Python-Analogon:

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

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

    return posts
Nach dem Login kopieren

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
Nach dem Login kopieren

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
Nach dem Login kopieren

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
Nach dem Login kopieren

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.

Blick zurück und nach vorne

Wenn ich über meinen Weg vom JavaScript-Entwickler zum Einstieg in Python nachdenke, bereue ich nichts. Dieser Übergang hat spannende Möglichkeiten eröffnet, insbesondere in den Bereichen KI und maschinelles Lernen, die ich jetzt in meinen Projekten, insbesondere im Backend, umfassend nutze.

Mit Blick auf die Zukunft sind die Möglichkeiten mit Python enorm. Ob es um Webentwicklung, Datenwissenschaft, Automatisierung oder tieferes Eintauchen in KI und maschinelles Lernen geht, Python bietet eine leistungsstarke und vielseitige Grundlage, auf der Sie aufbauen und neue Horizonte erkunden können.

Das obige ist der detaillierte Inhalt vonFullstack-Entwicklung: Python als JavaScript-Entwickler lernen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!