Java 开辟者的 Python 快速入门指南

打印 上一主题 下一主题

主题 913|帖子 913|积分 2739


目录

1. 语法基础差异

代码块界说

Java:
  1. public class Example {
  2.     public void method() {
  3.         if (condition) {
  4.             // code block
  5.         }
  6.     }
  7. }
复制代码
Python:
  1. def method():
  2.     if condition:
  3.         # code block
复制代码
主要区别:

  • Python 使用缩进来界说代码块,不必要花括号
  • Python 不必要分号末端
  • Python 不必要显式声明类(除非必要)
2. 变量声明和范例

Java:
  1. String name = "John";
  2. int age = 25;
  3. List<String> list = new ArrayList<>();
复制代码
Python:
  1. name = "John"    # 动态类型,无需声明
  2. age = 25
  3. list = []        # 列表声明更简单
复制代码
主要区别:

  • Python 是动态范例语言,不必要显式声明变量范例
  • Python 的变量可以随时改变范例
  • Python 的集合范例(列表、字典等)使用更简单
3. 面向对象编程

Java:
  1. public class Person {
  2.     private String name;
  3.    
  4.     public Person(String name) {
  5.         this.name = name;
  6.     }
  7.    
  8.     public void sayHello() {
  9.         System.out.println("Hello, " + this.name);
  10.     }
  11. }
复制代码
Python:
  1. class Person:
  2.     def __init__(self, name):
  3.         self.name = name
  4.    
  5.     def say_hello(self):
  6.         print(f"Hello, {self.name}")
复制代码
主要区别:

  • Python 使用 self 代替 Java 的 this
  • Python 不必要声明访问修饰符(public/private)
  • Python 使用 __init__ 作为构造函数
  • Python 的方法命名通常使用下划线命名法
4. 函数声明与调用

根本函数声明

Java:
  1. public class Example {
  2.     // 基本函数声明
  3.     public int add(int a, int b) {
  4.         return a + b;
  5.     }
  6.    
  7.     // 静态方法
  8.     public static void staticMethod() {
  9.         System.out.println("Static method");
  10.     }
  11.    
  12.     // 可变参数
  13.     public void printAll(String... args) {
  14.         for(String arg : args) {
  15.             System.out.println(arg);
  16.         }
  17.     }
  18. }
复制代码
Python:
  1. # 基本函数声明
  2. def add(a, b):
  3.     return a + b
  4. # 静态方法
  5. @staticmethod
  6. def static_method():
  7.     print("Static method")
  8. # 可变参数
  9. def print_all(*args):
  10.     for arg in args:
  11.         print(arg)
  12. # 带默认参数的函数
  13. def greet(name, greeting="Hello"):
  14.     print(f"{greeting}, {name}")
  15. # 关键字参数
  16. def person_info(**kwargs):
  17.     for key, value in kwargs.items():
  18.         print(f"{key}: {value}")
复制代码
5. 继承与多态

Java:
  1. public class Animal {
  2.     protected String name;
  3.    
  4.     public Animal(String name) {
  5.         this.name = name;
  6.     }
  7.    
  8.     public void makeSound() {
  9.         System.out.println("Some sound");
  10.     }
  11. }
  12. public class Dog extends Animal {
  13.     public Dog(String name) {
  14.         super(name);
  15.     }
  16.    
  17.     @Override
  18.     public void makeSound() {
  19.         System.out.println("Woof!");
  20.     }
  21. }
复制代码
Python:
  1. class Animal:
  2.     def __init__(self, name):
  3.         self.name = name
  4.    
  5.     def make_sound(self):
  6.         print("Some sound")
  7. class Dog(Animal):
  8.     def __init__(self, name):
  9.         super().__init__(name)
  10.    
  11.     def make_sound(self):
  12.         print("Woof!")
  13. # 多重继承示例
  14. class Pet:
  15.     def play(self):
  16.         print("Playing")
  17. class DomesticDog(Dog, Pet):
  18.     pass
复制代码
6. 集合操作

列表/数组操作

Java:
  1. List<String> list = Arrays.asList("a", "b", "c");
  2. Map<String, Integer> map = new HashMap<>();
  3. map.put("key", 1);
复制代码
Python:
  1. list = ["a", "b", "c"]
  2. dict = {"key": 1}
  3. # 列表操作
  4. list.append("d")
  5. list[0]  # 访问元素
  6. list[1:3]  # 切片操作
  7. # 字典操作
  8. dict["new_key"] = 2
复制代码
7. 特殊方法与装饰器

特殊方法(把戏方法)
  1. class Person:
  2.     def __init__(self, name):
  3.         self.name = name
  4.    
  5.     def __str__(self):
  6.         return f"Person: {self.name}"
  7.    
  8.     def __eq__(self, other):
  9.         if isinstance(other, Person):
  10.             return self.name == other.name
  11.         return False
复制代码
属性装饰器
  1. class Person:
  2.     def __init__(self):
  3.         self._name = None
  4.    
  5.     @property
  6.     def name(self):
  7.         return self._name
  8.    
  9.     @name.setter
  10.     def name(self, value):
  11.         self._name = value
复制代码
8. 非常处置惩罚

Java:
  1. try {
  2.     throw new Exception("Error");
  3. } catch (Exception e) {
  4.     System.out.println("Caught: " + e.getMessage());
  5. } finally {
  6.     // 清理代码
  7. }
复制代码
Python:
  1. try:
  2.     raise Exception("Error")
  3. except Exception as e:
  4.     print(f"Caught: {str(e)}")
  5. finally:
  6.     # 清理代码
复制代码
9. Python特有特性

列表推导式
  1. # 生成 1-10 的平方数列表
  2. squares = [x**2 for x in range(1, 11)]
复制代码
切片操作
  1. list = [1, 2, 3, 4, 5]
  2. print(list[1:3])    # 输出 [2, 3]
复制代码
多重赋值
  1. a, b = 1, 2
  2. x, y = y, x    # 交换变量值
复制代码
10. 快速入门发起


  • 重点关注 Python 的缩进规则
  • 风俗不使用范例声明
  • 多使用 Python 的内置函数和特性
  • 学习 Python 的列表推导式和切片操作
  • 使用 f-string 举行字符串格式化
  • 熟悉 Python 的命名规范(下划线命名法)
  • 理解 Python 的继承机制,特别是 super() 的使用
  • 把握 Python 的特殊方法(把戏方法)
  • 学习使用装饰器
  • 了解 Python 的非常处置惩罚机制
保举学习资源

记住,Python 推许简便和可读性,很多 Java 中的复杂结构在 Python 中都有更简单的实现方式。发起从简单的程序开始,逐步熟悉 Python 的特性和语法。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

西河刘卡车医

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表