1
2

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 5 years have passed since last update.

Pythonにおけるクラスの記法

Last updated at Posted at 2020-04-15

クラスの記法

class (クラス名):
    (スイート)

クラスは上記のように記述します。
クラス名とはその名の通りクラスの名前で、スイートとは単純文やメソッドなどの処理を記述する部分です。
メソッドは関数とほとんど同じ記法で記述できるものですが、関数とは違って一般にクラスの内部で記述されます(これ以上はわからない)。

実際にクラスを作ってみる

class Ball:
    def __init__(self):
        print('クラスを作成')

このようにして作成します。
selfはインスタンス変数と呼ばれる、そのクラス(オブジェクト)に属する変数を定義する際に使用します。
それではインスタンス変数を定義してみます。

class Ball:
    def __init__(self, c, s):
        self.color = c
        self.size = s
        print('作成')

インスタンス変数は

self.(インスタンス変数名)

のように定義します。
また、インスタンス変数は一般に__init__メソッドの中に定義するようです。

それではオブジェクトを作成してみます。

ball = Ball('RED', 20)
print(ball.color)
print(ball.size)

>>作成
>>RED
>>20
```

ここではballクラスにprintが含まれているので作成が表示されます
このようなクラスを用いてコードを再利用しながら記述量を減らしていくような手法をオブジェクト指向と呼びます(間違っている可能性大)

誤りを見つけた方はご指摘いただけますと幸いです

1
2
3

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?