未分類

python3 でクラスの初期化を __init__ で行う

投稿日:

python でクラスのオブジェクトを生成したとき、__init__ メソッドが呼び出される(コンストラクタ)

__init__ の引数には自身(self)を指定することが通例。

一方、オブジェクト破棄の際に呼び出されるデストラクタは、__del__ と書かれる。

class Car:
 def __init__(self):
  self.name = "Audi"
 def sayname(self):
  print("My name is " + self.name)

car = Car()
car.sayname()

結果

My name is Audi

-未分類

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

matplotlib で縦横の罫線を出力する

罫線を出力するには、pyplot.grid を使う。 例 import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 …

no image

tex でオーム記号を入力する方法

siunit のパッケージを使って、\si{\ohm} で入力する。 例 \usepackage{siunitx} \begin{document} \si{\ohm} \end{document} …

no image

tex で累乗根を入力する方法

$\sqrt[n]{2}$のようにする。 例 $\sqrt[n]{2}$ 結果

no image

C言語でchar文字列の長さを取得する (strlen)

strlen 関数を使って取得すればよい。sizeof という関数もあるが、strlen と振る舞いが異なるので注意。 例 #include<stdio.h> #include<strin …

no image

c++ で文字列を「区切り文字」を使って分ける方法

string の find を使って、区切り文字の場所を取得し、その位置で区切る。 例 #include <iostream> #include <string> using namesp …