杰瑞科技汇

Java转Python,如何快速上手?

Of course! This is a very common transition. Python is an excellent language, and its simplicity and power make it a favorite for many developers.

Java转Python,如何快速上手?-图1
(图片来源网络,侵删)

This guide will act as a bridge, translating your Java knowledge into Python. We'll cover the core concepts, highlighting the key differences in syntax and philosophy.


The Core Philosophical Difference: "Explicit vs. Implicit"

  • Java is Explicit: You tell the compiler everything. You declare types for variables, you specify access modifiers (public, private), and you use curly braces to define code blocks. This verbosity makes the code more rigid but also very clear about its structure.
  • Python is Implicit (or "Pythonic"): Python values readability and conciseness. It uses indentation to define blocks, has dynamic typing, and often uses conventions (like underscores for private members) instead of strict keywords. This leads to less boilerplate code.

"Hello, World!" and Basic Syntax

This is the first thing you'll notice.

Java

// File: HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Python

# File: hello_world.py
# No 'public' or 'static' needed.
# No 'class' is required for a simple script.
print("Hello, World!")

Key Takeaways:

  • No Semicolons: Statements end with a newline, not a semicolon.
  • Indentation is Law: Python uses indentation (spaces or tabs) to define blocks. No curly braces! This is enforced by the interpreter, not just style.
  • print() is a function: In Python 3, print is a function, so you use parentheses .

Variables and Data Types

Java (Statically Typed)

You must declare the type of a variable.

Java转Python,如何快速上手?-图2
(图片来源网络,侵删)
int age = 30;
String name = "Alice";
boolean isStudent = true;
double price = 19.99;

Python (Dynamically Typed)

You don't declare types. The type is inferred at runtime.

age = 30          # Python infers this is an int
name = "Alice"    # This is a str (string)
is_student = True # This is a bool (boolean)
price = 19.99     # This is a float

Key Takeaways:

  • No Type Declarations: You just assign a value to a variable name.
  • snake_case for Variables: The standard convention in Python is to use snake_case for variable and function names, not camelCase.

Data Structures

Java

  • Arrays: Fixed-size, homogeneous.
  • ArrayList: Dynamic-size, homogeneous.
  • HashMap: Key-value pairs.
import java.util.ArrayList;
import java.util.HashMap;
// ArrayList
ArrayList<String> names = new ArrayList<>();
names.add("Bob");
names.add("Charlie");
// HashMap
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 88);

Python

Python has built-in, powerful data structures that are more flexible.

  • Lists: Dynamic-size, heterogeneous (can hold different types). Like ArrayList.
  • Dictionaries: Key-value pairs. Like HashMap.
  • Tuples: Immutable (cannot be changed) lists. Like a read-only ArrayList.
  • Sets: Unordered collections of unique items.
# List (most common)
names = ["Bob", "Charlie", 123] # Can hold different types
names.append("David") # Add to the end
print(names[0]) # Access by index: "Bob"
# Dictionary
scores = {"Alice": 95, "Bob": 88}
scores["Charlie"] = 91 # Add or update a key-value pair
print(scores["Alice"]) # Access by key: 95
# Tuple (immutable)
point = (10, 20)
# point[0] = 15 # This would cause an error!
# Set
unique_numbers = {1, 2, 2, 3, 4} # Becomes {1, 2, 3, 4}

Key Takeaways:

Java转Python,如何快速上手?-图3
(图片来源网络,侵删)
  • Lists are your go-to for ordered collections.
  • Dictionaries are incredibly efficient for lookups by key.
  • Mutability is a key concept: Lists and Dictionaries are mutable. Tuples are not.

Control Flow (Conditionals and Loops)

The logic is the same, but the syntax is cleaner in Python.

Java

// For loop
for (int i = 0; i < 5; i++) {
    System.out.println("i is: " + i);
}
// For-each loop
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
    System.out.println(fruit);
}
// If-else
int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C or below");
}

Python

# For loop (iterating over a sequence)
for i in range(5): # range(5) generates 0, 1, 2, 3, 4
    print(f"i is: {i}") # f-string for formatting
# For-each loop (more direct)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# If-else (no parentheses, uses indentation)
score = 85
if score >= 90:
    print("A")
elif score >= 80: # 'elif' instead of 'else if'
    print("B")
else:
    print("C or below")

Key Takeaways:

  • for loops are different: Python's for loop is like a Java enhanced for-loop. It iterates directly over items in a sequence. To get a C-style for loop, you use range().
  • f-strings are amazing: f"my variable is {variable}" is the modern, preferred way to format strings in Python.
  • No Parentheses or Semicolons in if/elif/else conditions.

Methods (Functions in Python)

Java

public class Calculator {
    // Method with a return type
    public static int add(int a, int b) {
        return a + b;
    }
    // Method without a return type (void)
    public static void printGreeting(String name) {
        System.out.println("Hello, " + name);
    }
}

Python

Functions are defined using the def keyword. No public, static, or void.

# Function definition
def add(a, b):
    # Indentation defines the function body
    return a + b
# Function that doesn't return anything (implicitly returns None)
def print_greeting(name):
    print(f"Hello, {name}")
# How to call them
sum_result = add(5, 3)
print_greeting("Eve")

Key Takeaways:

  • Use def to define a function.
  • Type hints are optional but becoming more common: def add(a: int, b: int) -> int:
  • snake_case for function names.

Object-Oriented Programming (OOP)

This is where the differences become more pronounced.

Java

public class Dog {
    // Member variables (fields)
    private String name;
    private int age;
    // Constructor
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // Public method (getter)
    public String getName() {
        return this.name;
    }
    // Public method (behavior)
    public void bark() {
        System.out.println("Woof! My name is " + this.name);
    }
}

Python

Python has classes, but the syntax is different. There's no public/private keyword. Convention is used instead.

  • A single underscore _ prefix suggests "internal use, please don't touch."
  • A double underscore __ prefix triggers "name mangling" (a form of privacy).
class Dog:
    # The __init__ method is the CONSTRUCTOR
    # 'self' is like 'this' in Java
    def __init__(self, name, age):
        self.name = name  # 'self.name' is the instance variable
        self._age = age   # Convention for "private"
    # A method with a single underscore is "protected" by convention
    def _get_age(self):
        return self._age
    # A public method
    def bark(self):
        # f-strings make this easy
        print(f"Woof! My name is {self.name}")
    # A "getter" method (less common in Python than in Java)
    def get_name(self):
        return self.name

Key Takeaways:

  • self is mandatory: It's the first parameter of any instance method, representing the object itself (like this).
  • No Constructors: The __init__ method is the initializer, not technically a constructor (the object is already created when __init__ runs).
  • Privacy by Convention: Use underscores for privacy. Python trusts you to be an adult.
  • No new keyword: You just call the class name: my_dog = Dog("Rex", 5).

The Standard Library: " batteries included "

Python's standard library is one of its greatest strengths. It's vast and covers almost everything you need.

Java Concept (java.lang, java.util) Python Equivalent (Built-in / Standard Library)
System.out.println() print()
String methods str methods (e.g., "hello".upper())
ArrayList list
HashMap dict
Arrays.asList(...) [...] (list literal)
Files.readAllLines() with open("file.txt") as f: f.readlines()
Math.random() import random; random.random()
JSON.parse() import json; json.loads()
try-catch-finally try-except-finally

Example: File I/O

Java

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
try {
    String content = Files.readString(Paths.get("myfile.txt"));
    System.out.println(content);
} catch (IOException e) {
    e.printStackTrace();
}

Python

# The 'with' statement automatically handles closing the file
try:
    with open("myfile.txt", "r") as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print("The file was not found.")

Tooling and Ecosystem

  • Build Tools:
    • Java: Maven, Gradle.
    • Python: pip (for packages), venv or conda (for virtual environments), and pipenv or poetry (which combine package and environment management).
  • Package Management:
    • Java: Central Repository (Maven Central).
    • Python: Python Package Index (PyPI). You install packages with pip install requests.
  • Popular Frameworks:
    • Backend: Java (Spring Boot), Python (Django, Flask, FastAPI).
    • Data Science: Java (less common), Python (Pandas, NumPy, Scikit-learn, TensorFlow, PyTorch) - Python dominates this space.
    • Web Scraping: Java (Jsoup), Python (Beautiful Soup, Scrapy) - Python is king here.

Summary: Java vs. Python at a Glance

Feature Java Python
Typing Static Dynamic
Syntax Verbose, explicit Concise, "Pythonic"
Code Blocks Curly Braces Indentation
Main Method public static void main(String[] args) Script-level code (or if __name__ == ...)
Variables int x = 5; x = 5
Lists ArrayList<String> list = new ArrayList<>(); my_list = ["a", "b"]
Dictionaries HashMap<String, Integer> map = ...; my_dict = {"key": "value"}
Methods public int add(...) def add(...):
OOP this this self
Strings "name" + variable f"name is {variable}"
Error Handling try-catch try-except
Philosophy "Write once, run anywhere" (WORA) "Simple is better than complex"
分享:
扫描分享到社交APP
上一篇
下一篇