pythonでの関数の呼び出し
def some_function(something):
print(something)
some_function("hello world")
Classにした場合
L インスタンスを生成して処理を実行する
L クラスの中の関数をメソッドと呼ぶ
class SomeClass:
def __init__(self, something):
self.something = something
def some_function(self):
print(self.something)
c = SomeClass("hello world")
c.some_function()
class SomeClass:
def __init__(self, something):
self.something = something
def some_function(self):
print(self.something)
def some_function2(self):
return self.something
c = SomeClass("hello world")
c.some_function()
print(c.some_function2())
selfはインスタンス自身のこと
initはデータの初期化の関数
class MyStatus:
def __init__(self, age, name, height, weight):
self.age = age
self.name = name
self.height = height
self.weight = weight
def print_name(self):
print(self.name)
def print_age(self):
print(self.age)
def print_height(self):
print(self.height)
def print_weight(self):
print(self.weight)
a = MyStatus(14, "yamada", 160, 55)
a.print_height()
コーヒーメーカーのClassを作ってみる
class CoffeeMaker:
def __init__(self, water, brand, tempreture):
self.water = water # mill
self.brand = brand
self.tempreture = tempreture
def boiling(self):
boilingTime = self.water / 10 * self.tempreture
print(boilingTime)
def brew(self):
print(self.brand + "を滴れました")
a = CoffeeMaker(300, "brend", 3)
a.boiling()
a.brew()
$ python3 test.py
90.0
brendを滴れました
なるほど、Classと関数とinitの使い方について、自分で例を作ると構造を理解できますね。
phpの場合はinitのところが__contructになります。引数はconstructで定義しています。
class Dog {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName(){
echo $this->name;
}
}
$dog = new Dog(“Pochi”);
$dog->getName();
[/code]
ini_set('display_errors', "On");
class CoffeeShop {
private $order;
private $pay;
public function __construct($order, $pay) {
$this->order = $order;
$this->pay = $pay;
}
public function coffeePrice(){
switch ($this->order) {
case "ブレンド":
echo "price is 330 yen\n";
$price = 330;
break;
case "アメリカン":
echo "price is 350 yen\n";
$price = 350;
break;
case "アイスコーヒー":
echo "price is 380 yen\n";
$price = 380;
break;
default:
echo "not available at this store";
}
$change = $this->pay - $price;
return $change;
}
}
$a = new CoffeeShop("ブレンド", 1000);
$b = $a->coffeePrice();
echo $b;