自己投資の一つとしてチャレンジしている Programming の独習状況を Blog で公開しています。今回は Python を Visual Studio Code (VS Code) で実行するにあたり Class と Object について確認したことをまとめます。
————————————
▼1. Python の Class と Object について
————————————
Python ではすべてのものが Object と言えます。例えば データ型 String, Boolean, number などや function (いわゆる method) も Object となります。
Object とは、データや変数、method などの総称 (collection)。
Class とは、1 つ以上の Object のもととなるもの。Python のすべての object は class が基となります。
Object を作ることは、いわゆる、Class のインスタンスを作ることであり、データ型 string, number や boolean なども Class のインスタンスとなります。ユーザーも自由に Class を作る事ができます。確認方法として、 “CTRL” と “SHIFT” と “p” のキーを同時に押し、”Python: Start REPL” を選択後、 REPL Terminal 上で以下を実行し確認します。
>>> type('a')
<class 'str'>
>>> type(1)
<class 'int'>
>>> type(True)
<class 'bool'>————————————
▼2. 事前準備
————————————
2-1. Ubuntu 20.04.2 LTS の利用
https://releases.ubuntu.com/20.04/
2-2. Visual Studio Code のインストール
https://code.visualstudio.com/docs/setup/linux
sudo snap install --classic code2-3. Python extension のインストール
Get Started Tutorial for Python in Visual Studio Code
インストールした Python のバージョンを確認
python3 --version
(実行結果)
Python 3.8.52-4. Python インタプリター のインストール
Installation – pip documentation v21.1.3 (pypa.io)
python get-pip.py
————————————
▼3. Python で Class や Object を作る
————————————
3-1. “CTRL” と “SHIFT” と “p” のキーを同時に押し、”Python: Start REPL” を選択、その後 REPL Terminal 上で以下を実行し、Motorcycle の Class を作ります。以下例となります。
class Motorcycle:
speed = 0
started = False
def start(self):
self.started = True
print("Motorcycle started, let's ride!")
def increase_speed(self, delta):
if self.started:
self.speed = self.speed + delta
print('Brooooom!')
else:
print("You need to start the Motorcycle first")
def stop(self):
self.speed = 0
print('Halting')
3-2. Motorcycle の Class の instance を作り、言い換えると object を作り、Motorcycle の object の method を REPL Terminal 上で実行していきます。以下実行例となります。
/PythonCode/hello$ /bin/python3
Python 3.8.10 (default, Jun 2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Motorcycle:
... speed = 0
... started = False
...
... def start(self):
... self.started = True
... print("Motorcycle started, let's ride!")
...
... def increase_speed(self, delta):
... if self.started:
... self.speed = self.speed + delta
... print('Booooom!')
... else:
... print("You need to start the Motorcycle first")
...
... def stop(self):
... self.speed = 0
... print('Halting')
...
>>> mtc = Motorcycle()
>>> mtc.increase_speed(10)
You need to start the Motorcycle first
>>> mtc.start()
Motorcycle started, let's ride!
>>> mtc.increase_speed(40)
Booooom!
>>> mtc.stop()
Halting
>>> ————————————
▼4. 参考情報
————————————
(1) BeginnersGuide/Programmers – Python Wiki
(2) Classes and Objects in Python • Python Land Tutorial
以上です。参考になりましたら幸いです。