未分類

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

python3 で、文字列の最後が特定の文字で終わるか判定する方法

endswith を使う。 例 str1 = “こんにちは” result1 = str1.endswith(“は”) result2 = str1.endswith(“わ”) print(resul …

no image

c++ で文字列が他の文字列を含むか判定する方法

文字列を含むかどうか判定するには、string の find を使う。見つからなかった場合は、std::string::npos を返す。 例 #include <iostream> #i …

no image

python3 で文字列を区切り文字を指定してリストに変換する方法

split メソッドを使う。 例 str1 = ‘this, is, a, pen’ str2 = str1.split(‘,’) print(str2) 結果 [‘this’, ‘ is’, ‘ a …

no image

python で文字列の長さを表示する方法

len を使う。 例 length = len(‘文字列あいうえお’) print(str(length)) 結果 8

no image

tex で数式モード内に普通の文字列を入力する方法

\textrm を使う。 例 $$y = f (x) \hspace{1cm} \textrm{This is a function.}$$ 結果