4
2

More than 3 years have passed since last update.

Java屋さんのためのPython Syntaxチートシート

Last updated at Posted at 2020-08-24

最近Pythonをはじめました。
が、やりたいことはググると出てくるし、Python3に至ってはオブジェクト指向になってくれたおかげで、だいたいは雰囲気つかめちゃったりするので良いのですが、いざ書いてみると躓くのは文法だったりしますよね?(私だけ?)
だいたいJavaに慣れきってたりすると、Javaだとああ書くんだけど、Pythonだとどう書くんだろ?的な発想になるので、似たようなことを考えてる人のお役に立てれば幸いです。

というわけで、Javaだとこう書いてたけど、Python3だとこう書くんだよ、というのを残しておきます。
始めたばっかりなので、多少考え方とか間違ってるかもしれないけど、そのへんはご愛嬌。ざっくりです。書きながら覚えていくタイプなんで。
気が向いたら更新していくと思います。

環境

Python 3.8
Java 8

公式のチュートリアル

公式のユニットテスト(unittest)

チートシート

コメント

Java

// 行単位のコメント
/*
 * ブロックコメント
 */

Python

# コメント

クラス定義

Java

public class Hoge {

}

Python

class Hoge:  # コロンが大事!!

コンストラクタ定義

Java

public Hoge(){
  // 初期化すんよ
} 

Python

(追記)Pythonの場合はコンストラクタというより、メソッドだそうです。
コンストラクタの中から呼ばれるメソッド、と思ったほうが良さそう

def __init__(self):
  # 初期化すんよ

インスタンス生成

Java

Hoge hoge = new Hoge();

Python

hoge = Hoge()

処理起点(いわゆるメイン)

Java

public static void main(String[] args) {
    // body of main()
}

Python

if __name__ == "__main__":
  hoge.hoge()

他のモジュール(クラス)を使いたい

Java

import jp.co.hoge.Hoge;

Python

なんか書き方いっぱいある・・・!
https://nansystem.com/python-module-package-import/

条件式

Java

// a = b and b = c
if (a == b && b == c) {
  System.out.println(a)
}

// a = b or b = c
if (a == b || b == c) {
  System.out.println(a)
}
// 否定
if (!enable) {
  System.out.println(a)
}

Python

# a = b and b = c
if a = b and b = c:
  print(a)

# a = b or b = c
if a = b or b = c:
  print(a)

# 否定
if not enable:
  print(a)

比較演算子

比較演算子はJavaもPythonも一緒

<  <=   >   >=   ==   !=

null と None

Javaのnullはオブジェクトがない
PythonのNoneは 値がない
をそれぞれ意味する

In Java, null is an instance of nothing, it is often referred as "no object" or "unknown" or "unavailable" .

In Python None is an object, denoting lack of value. This object has no methods. It needs to be treated just like any other object with respect to reference counts.

So these two are not much alike, however since Java 8 Optional has come along which is more similar to None. It is a class that encapsulates an optional value.
You can view Optional as a single-value container that either contains a value or doesn't (it is empty)

厳密にはnullとNoneは意味が違うので同じようには使えない、NoneはJavaでいうところのOptionalが近い。

While the difference is nuanced, Python's None by being an object itself, helps avoid some types of programming errors such a NullPointerExceptions in Java.

ただ、Noneはオブジェクトなので、ぬるぽ処理みたいなことに役立つよ

という話らしい。

文字列の空白・null判定

PythonはnullじゃなくてNoneだけど。
https://pg-chain.com/python-null

Java

// str != null && str != ""
if (str.isEmpty()) {
  return true;
}

Python

if not str:
  return True
else
  return False

エラー

https://docs.python.org/ja/3/tutorial/errors.html
既定クラスはJavaもPythonもExceptionクラス

java

try {
  // 例外が起きる処理
} catch (Exception e) {
  e.printstacktrace();
  throw new CustomizeException();
} finally {
  // 最後にしておきたい処理
}

Python

try:
  // 例外が起きる処理
except Exception as e:
  print(e)

リスト

PythonのリストはJavaの配列とArrayListのいいとこ取りした感じのやつっぽい。
書き方はJavaの配列に似ている。
Pythonには配列型もあって、こっちがJavaの配列とほぼ同じなのかな。配列型は標準では使えず、インポートが必要。

Java

List<String> list = new ArrayList<>;

// 配列の長さを取得
list.size();

// リストに追加
list.add("lemon");

Python

l = ["John", "Bob", "Carry"]

# リストの要素数を取得(len関数を使う)
len(l)

# リストに追加
l.append("Mickey")

Map → 辞書

JavaでいうところのMapはPythonの辞書(dict)にあたる。
https://docs.python.org/ja/3/tutorial/datastructures.html

Java

Map<String, String> map = new HashMap<>();

Python

# 波括弧{}で作成する場合
d = {'key1': 'aaa', 'key2': 'bbb'}

# コンストラクタでも作れる
d2 = dict()
d3 = dict('k1'='aaa', 'key2'='bbb')
# 他にもいろいろ書き方あり

文字列 → 数値変換

整数の場合は int()、浮動小数点の場合は float()を使う
https://note.nkmk.me/python-str-num-conversion/

Java

int month = Integer.valueOf("01");
// または
int month = Integer.parseInt("01");

Python

month = int('01')

数値 → 文字列変換

str()を使えばいい
https://note.nkmk.me/python-str-num-conversion/

Java

String month = Integer.toString(1);
// または
String month = new String(1);

Python

month = str('01')

その他 いろいろ参考になったサイト

参考

https://qiita.com/karadaharu/items/37403e6e82ae4417d1b3
https://www.rose-hulman.edu/class/cs/csse220/200910/Resources/Python_vs_Java.html
https://python.keicode.com/lang/oop-basics.php

謝辞

@shiracamus さんありがとうございます

4
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2