这里的学习背景是学会了 java,但是不会 Python 的语法
类比的方式来讲 Python 的语法,这样更容易上手。用 twoSum 例子来展开说说 Python 和 Java 的异同。
一、类定义和方法
Java:
public class Solution {
public int[] twoSum(int[] nums, int target) {
// ...
}
}
Python:
class Solution(object):
def twoSum(self, nums, target):
# ...
对比解释:
class Solution(object)
:定义一个类,object
是所有类的基类(可以省略)。def
是 Python 中定义方法(函数)的关键词,相当于 Java 里的public
+ 返回类型。self
是 Python 类中方法的第一个参数,表示类的实例,相当于 Java 里的this
。Python 不需要写返回类型(Python 是动态类型语言)。
二、注释的写法
"""
:params nums: List[int]
:params target: int
:return: List[int]
"""
这个是文档字符串,可以帮助别人理解函数的参数和返回值。和 Java 中的 javadoc 比较像:
/**
* @param nums 输入数组
* @param target 目标值
* @return 两个数的下标
*/
三、语法格式(很关键)
Python:
不需要大括号
{}
,而是用缩进(通常是4个空格)表示代码块。结尾不需要分号
;
变量声明不需要写类型,比如
a = 1
就可以了。
四、一个完整的 Python 实现(对照 Java 思维)
class Solution(object):
def twoSum(self, nums, target):
hashmap = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap:
return [hashmap[complement], i]
hashmap[nums[i]] = i
Java 类比版:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return null;
}
五、常见语法小贴士
Java | Python |
---|---|
public int x = 0; |
x = 0 |
if (a == b) {} |
if a == b: |
for (int i = 0; i < n; i++) |
for i in range(n): |
String s = "abc"; |
s = "abc" |
System.out.println() |
print() |
self
✅ 先看 Java 中的例子:
public class Dog {
String name;
public Dog(String name) {
this.name = name;
}
public void bark() {
System.out.println(this.name + " is barking!");
}
}
在这个类中:
this.name
就是指这个“Dog”对象自己的name
。this
就是当前实例对象(new 出来的那只狗)。
🔁 对应到 Python 中:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + " is barking!")
解释:
self
就相当于 Java 里的this
。self.name = name
就是把传进来的名字赋值给当前实例对象。在调用
bark()
的时候,self
会自动表示当前这只狗。
🧠 举个完整例子来理解 self
:
dog1 = Dog("Lucky")
dog2 = Dog("Snowy")
dog1.bark() # 输出:Lucky is barking!
dog2.bark() # 输出:Snowy is barking!
在执行 dog1.bark()
时,Python 会自动把 dog1
作为第一个参数传给 bark()
方法的 self
,所以:
self = dog1
✅ 所以总结一下:
Java | Python |
---|---|
this.name = name; |
self.name = name |
public void bark() |
def bark(self): |
自动传入当前对象 this |
自动传入当前对象 self |
可以试着把 self
暂时当成 Java 里的 this
,只不过在 Python 里必须手动写出来作为第一个参数(这是语法规定),而 Java 是隐式存在的。