1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クラスの定義

Last updated at Posted at 2020-08-25

クラスの作り方

personというクラスを作る

qiita.py
class Person(object):
    def say_something(self):
        print("hello")

person = Person()
person.say_something()

python3以降では以下のように書いても同様の結果が得られる

qiita.py
class Person:
    def say_something(self):
        print("hello")

class Person():
    def say_something(self):
        print("hello")

クラスの初期化

クラスが作られた時点で実行される
この中で初期設定をしていく

qiita.py
class Person(object):
    def __init__(self):
        print("first")

    def say_something(self):
        print("hello")

person = Person()
# person.say_something()

スクリーンショット 2020-08-16 19.21.03.png

クラス変数

personというオブジェクトに値を保持させたいとき
selfを使う 

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name
        print(self.name)

    def say_something(self):
        print("hello")

person = Person("kirin")

関数と同様に引数を必要としているため、与えないとエラーが起きる

qiita.py
 def __init__(self,name):
        self.name = name
        print(self.name)

実行結果
スクリーンショット 2020-08-16 19.32.06.png

クラスのメソッドはselfを用いて値を引き継いでいく
一度selfで値保持すると同じクラス内の関数で使える

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name
        print(self.name)

    def say_something(self):
        print("I am {}. hello".format(self.name))

person = Person("kirin")
person.say_something()

実行結果
スクリーンショット 2020-08-16 19.36.59.png
自分自身のメソッドを読み込む事も可能

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name

    def say_something(self):
        print("I am {}. hello".format(self.name))
        self.run()#自分自身のメソッドにアクセス


    def run(self):
        print("run")

person = Person("kirin")
person.say_something()
# say_somethingを呼び出す

実行結果
スクリーンショット 2020-08-16 19.41.14.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?