未分類

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

tex で、表のキャプション内で改行する方法

\newline を使って次のように書く。 例 \begin{table} \begin{tabular}{ |c|c|c|c| } \hline 1 & 2 & 3 \\ \hlin …

no image

tex の積分範囲の分数サイズを変更する方法

定積分の分数の大きさを調整するには、\mbox のサイズ指定を \small や \normalsize や \large 等に設定すると良い。 例 $\displaystyle \int _0 ^{ …

no image

tex で脚注を表示する方法

\footnote を使う。 例 \footnote{this is a footnote.} 結果

no image

tex で文字の上の点を入力する方法

テキストモードでは \. 数式モードでは \dot{} を使う。 例 \.{a}$\dot{x}$ 結果

no image

c++ で文字列(string)の長さを取得する方法

length() で取得する。 例 #include <iostream> #include <string> using namespace std; int main () { str …