[A-00195] python入門
pythonの入門用記事です。
主に仮想環境(venv)で実行します。
・helloworldしてみる。
適当なディレクトリにvenvを作成します。作成方法は下記の記事参照
実行プログラムを作成します。
print("hello,python")
(.venv) $ python3 hello.py
hello,python
・クラスを作成してみる
pythonのクラスの作成方法と使い方についてです。
ディレクトリ階層も使ってクラスを作成します。

今回作成するクラスはclsディレクトリ配下におきます。ディレクトリをパッケージ名として認識させるため__init__.pyを作成しておいておきます。中身は空で良いです。

次にperson.pyを作成します。
class Person():
def __init__(self, name, age, country):
self.__name = name
self.__age = age
self.__country = country
def introduce(self):
print("My name is " + self.__name + ". Nice to meet you.")
print("I'm " + str(self.__age) + " years old.")
print("I'm live in " + self.__country + ".")
def getName(self):
return self.__name
def getAge(self):
return self.__age
def getCountry(self):
return self.__country
実行プログラムを作成します。
from cls.person import Person
if __name__ == '__main__':
p1 = Person("satoshi", 14, "Japan")
p1.introduce()
実行結果は下記の通りです。
(.venv) $ python3 main.py
My name is satoshi. Nice to meet you.
I'm 14 years old.
I'm live in Japan.
・インターフェースっぽいクラスを作成してみる
pythonにinterface修飾子はないのでそれっぽいやつを作ります。
ディレクトリ構成は下記の通り

import abc
class Person(metaclass=abc.ABCMeta):
@abc.abstractmethod
def sayHello(self) -> None:
raise NotImplementedError()
from cls.person import Person
class BusinessPeron(Person):
def __init__(self, name):
self._name = name
def sayHello(self):
print("Hello, my name is " + self._name + ". Nice to meet you.")
from cls.business_person import BusinessPeron
if __name__ == '__main__':
bp1 = BusinessPeron("satoshi")
bp1.sayHello()
実行結果はこちら
(.venv) $ python3 main.py
Hello, my name is satoshi. Nice to meet you.
・Appendix
参考文献はこちら
https://www.javadrive.jp/python/string/index9.html
https://qiita.com/hiroyuki_mrp/items/4b7102709e6582b9dd15
https://envader.plus/article/16
https://zenn.dev/plhr7/articles/36ddd240ccbb97
コメントを残す