Java和Python的语法比较
| Java | Python | |
| 编译 | 编译:
javac MyClass.java java MyClass |
解释:
python MyProgram.py |
| 变量 | 必须声明的变量(静态类型) | 没有声明(动态类型) |
| 代码风格 | 代码风格:鼓励缩进 | 代码风格:必须缩进 |
| 备注 | 备注:使用 // | 使用#号 |
| 文件名 | 文件名: 必须与类的名字一致 | 没有要求 |
| 语句结尾 | 所有的语句后面需要以 分号结束 | 不需要分号 |
| 程序与类 | 程序必须要嵌入到类里面 | 不需要 |
| 打印字符串 |
System.out.printf(“Student: %s ~ ID: %d%n”, name, id); Student: Arthur ~ ID: 731137 |
print “Student: %s ~ ID: %d” %(name, id) or print “Student:”, name, “~ ID:”, id |
| If语句 |
if (cond) { a = a + 1; cond = false; } else if (!cond) { a = a – 1; } q = 17; |
if cond: a = a + 1 cond = 0 elif not cond: a = a – 1 q = 17 |
| 代码环绕 |
使用进行{ }进行环绕 if (cond) { a = a + 1; cond = false; } |
使用: if cond: a = a + 1 cond = 0 elif not cond: a = a – 1 q = 17 |
| 条件内容 | 使用()来围住 if (cond) | no |
| 布尔值 | true , false | True,False |
| 逻辑操作符&&, || ,!的使用 | if (a<b) && (b<c) {..}
if (a==2) || (a==3) {..} if (!found_item) {..} |
if a==2 or a==3:
.. if not found_item: |
| While语句 |
s = “”; while (counter > 0) { s = s + “O”; counter–; } mystring = s; |
s = “”
while counter > 0: s = s + “O” counter -= 1 mystring = s NB: a string with 5 O’s can be created with 5 * “O” |
| For语句 |
int s = 0 for (int i=0; i<10; i++) { s = s + i; } |
s = 0 for i in range(10): s += i NB: can’t use ++ , use += 1 instead |
| 类和对象 |
public class DNA { public static int dna_objects; //class var. private int length; //object var.
public DNA() { //constructor length = 0; } ..
public int getLength() { return length; } }
DNA dna = new DNA(); |
class DNA: dna_objects = 0 # class variable
def __init__(self): # constructor self.length = 0 # object variable ..
def getLength(self): return self.length
dna = DNA() |
| 私有,公共属性和方法 | private, public fields and methods | everything is public |
| 类的类型 | class variables declared static | object variables must be prefixed with self. and should be initialized in constructor,
class variables do not have prefix and are initialized in class definition |
| This&Self | 关键字this是指类本身 | Self必须是所有函数的第一个参数,外部调用函数时候不需要写self |
| 构造器 | 构造器与类同名 | __init__等价于构造器 |
| 如何构建对象 | 使用new DB = new DB() | DB = db() |
嗯,比较的挺好的,一直用Python,最近考试看了几天Java,回来再用好多语法都搞混了,正好可以理一理呢
Python的语法有点像VB