LoginSignup
1
1

More than 3 years have passed since last update.

pythonのインスタンスについて

Posted at

pythonのインスタンス(instance)

(例)userの特徴を保存しておく場合

クラスを作成する(おすすめ)

以下のように名前,身長,体重,性別などをたくさんの人の情報を保持したい

"""
正しい書き方
"""
class User:
    def __init__(self, name, height):
        self.name = name
        self.height = height

インスタンスを生成する

mainで以下のように呼び出す事でインスタンス(instance)を生成できる
これはuser1というinstance(例という意味)を生成している

user1 = User #とりあえずインスタンスを生成
user1.name = "hoge" #後からname,heightを代入
user1.height = "foo"

user1 = User("hoge","foo") #あらかじめ代入可能

initを定義しているので

user1 = User("tarou","175")
user2 = User("hanako","140")

のように複数のインスタンスを作成する事ができる!!

クラスを生成する(微妙)

"""
あんまり良くない書き方
"""
class User:
    name = "hoge"
    height ="foo"

上記のように書くと

user1 = User
user2 = User

のように複数のインスタンスを生成した場合,変数を同期してしまう

つまり以下のようにuser1とuser2の名前の設定をしたのに

user1.name = "tarou"
user2.name = "hanako"

出力すると

print(user1.name)

>> hanako

hanakoが出力されてしまう

インスタンスやクラスを知ると便利なことが多いので基礎的な事に注意したい

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1