- Java
class Foo {
//
}
- Python
class Foo:
pass # 内部的にはクラスオブジェクトが実行される (インスタンスが出来る訳ではない)
class Foo {
//
}
class Foo:
pass # 内部的にはクラスオブジェクトが実行される (インスタンスが出来る訳ではない)
class Foo {
int x;
void setX(int x) {
this.x = x;
}
int getX() {
return x;
}
}
Foo foo = new Foo();
foo.setX(1);
foo.getX(1); // => 1
class Foo:
# フィールドの定義は不要
def set_x(self, x): # 第一引数に自インスタンスを指定する self
self.x = x # self という変数名は慣習
def get_x(self):
return self.x
# python には new 演算子が無い
foo = Foo()
foo.set_x(1)
foo.get_x() # => 1
list = [x for x in range(5)] # 0~4までのリストを作成 |
//
int num = 0; // int型
String str = "abc"; // String型(C#の場合string)
num = str; // Compilation Error
num = 0
str = "abc"
num = str # OK
"hello!"
'hello!!'
"hello!!"
int[] array = new int[3];
array[0] = 1;
array = [1, 2, 3]
array[-1] # 3
int[] array = {{1, 2}, {3, 4}};
array = [[1, 2], [3, 4]]
if (condition) {
// true
}
if condition:
# true
for (int i; i < 3; i++) {
// statement
}
for i in range(3):
# statement
for (int n : array) {
// statement
}
for n in array:
# statement
while (condition) {
// statement
}
while condition:
# statement
void func() {
}
void func(int i) {
}
int func() {
return 0;
}
int func(int i) {
return 0;
}
# defで関数を宣言する
def func():
pass # pass を書かないとエラーになる (定義を書いたところで内部実行されオブジェクトとして扱われる)
# インデントは必須
def func(i):
pass
def func():
return 0
def func(i):
return 0
class Hello { | |
public static void main(String[] args) { | |
System.out.println("Hello Python!"); | |
} | |
} |
print("Hello Python!") |
def double(n): | |
return n * 2 | |
def triple(n): | |
return n * 3 | |
double(2) # 4 | |
triple(2) # 12 | |
# 変数に関数を入れることができる | |
d = double | |
d(2) | |
# 引数に関数を入れることもできる | |
list(map(double, [1, 2, 3])) # [2, 4, 6] |
class Node: | |
def __init__(self, data=None): # Noneは null を指すオブジェクト | |
self.data = data | |
self.next = None | |
class LinkedList: | |
def __init__(self): | |
self.head = None | |
def add_first(self, data): | |
new_node = Node(data) | |
new_node.next = self.head | |
self.head = new_node | |
def remove(self, remove_key): | |
head = self.head | |
if head is not None: | |
if (head.data == remove_key): | |
self.head = head.next | |
head = None | |
return | |
while head is not None: | |
if head.data == remove_key: | |
break | |
prev = head | |
head = head.next | |
if head == None: | |
return | |
prev.next = head.next | |
head = None | |
def print_all(self): | |
printval = self.head | |
while printval: | |
print(printval.data), | |
printval = printval.next | |
list = LinkedList() | |
list.add_first("Mon") | |
list.add_first("Tue") | |
list.add_first("Wed") | |
list.add_first("Thu") | |
list.remove("Tue") | |
list.print_all() |