Python基礎 オブジェクト指向(その1)
| 登録日 | :2025/09/16 04:42 |
|---|---|
| カテゴリ | :Python基礎 |
オブジェクト指向プログラミングの基礎。サンプルプログラム。
sample1
プロパティメソッドの使い方
class Employee(object):
def __init__(self, _emp_id: int = None, _name: str = None, _salary: int = None) -> None:
self.__emp_id = _emp_id
self.__name = _name
self.__salary = _salary
# def get_salary(self) -> int:
# return self.__salary
#
# def set_salary(self, _salary: int) -> None:
# self.__salary = _salary
@property
def salary(self) -> int:
return self.__salary
@salary.setter
def salary(self, _salary: int) -> None:
if not isinstance(_salary, int):
raise TypeError("Name must be a integer")
self.__salary = _salary
@staticmethod
def work() -> None:
return None
if __name__ == '__main__':
employee = Employee(1, 'Jun', 100)
print(employee.salary)
employee.salary = 200
print(employee.salary)
# employee.salary = '100'
sample2
抽象クラス(インターフェース)の使い方
from abc import ABCMeta, abstractmethod
class IShape(metaclass=ABCMeta):
@abstractmethod
def calc_area(self) -> int:
pass
class Rectangle(IShape):
def __init__(self, _width: int, _height: int):
self.__width = _width
self.__height = _height
def calc_area(self) -> int:
return self.__width * self.__height
class Square(IShape):
def __init__(self, _length: int):
self.__length = _length
def calc_area(self) -> int:
return self.__length * self.__length
class Client(object):
def __init__(self, _shape: IShape):
self.shape = _shape
if __name__ == '__main__':
rec = Rectangle(10, 20)
squ = Square(10)
client = Client(rec)
print(client.shape.calc_area())
client = Client(squ)
print(client.shape.calc_area())