March 19

Перегрузка операторов. Статические методы

# Статические методы

class MathUtils:
	@staticmethod
	def add(x: float, y: float) -> float:
		return x + y

	@staticmethod
	def subtract(x: float, y: float) -> float:
		return x - y

	@staticmethod
	def multiply(x: float, y: float) -> float:
		return x * y

	@staticmethod
	def divide(x: float, y: float) -> float:
		return x / y


def main():
	addition = MathUtils.add(8, 11)
	subtraction = MathUtils.subtract(9, 15)
	multiplication = MathUtils.multiply(4, 10)
	division = MathUtils.divide(63, 7)

	print(addition, subtraction, multiplication, division, sep = '\n')


if __name__ == '__main__':
	main()
# Перегрузка операторов

class Fraction:
	# Конструктор класса Fraction
	def __init__(self, numerator: float, denominator: float) -> None:
		self.numerator = numerator
		self.denominator = denominator

	#  Перегрузка оператора '+'
	def __add__(self, other: 'Fraction') -> 'Fraction':
		return Fraction(
			numerator = self.numerator * other.denominator + self.denominator * other.numerator,
			denominator = self.denominator * other.denominator
		)

	# Перегрузка оператора '-'
	def __sub__(self, other: 'Fraction') -> 'Fraction':
		return Fraction(
			numerator = self.numerator * other.denominator - self.denominator * other.numerator,
			denominator = self.denominator * other.denominator
		)

	# Перегрузка оператора '*'
	def __mul__(self, other: 'Fraction') -> 'Fraction':
		return Fraction(
			numerator = self.numerator * other.numerator,
			denominator = self.denominator * other.denominator
		)

	# Перегрузка оператора '/'
	def __truediv__(self, other: 'Fraction') -> 'Fraction':
		return Fraction(
			numerator = self.numerator * other.denominator,
			denominator = self.denominator * other.numerator
		)

	# Обработка конвертации объекта класса в строку
	def __str__(self) -> str:
		return f'{self.numerator}/{self.denominator}'


def main():
	a = Fraction(1, 2)
	b = Fraction(5, 7)

	print(f'{a} + {b} = {a + b}')
	print(f'{a} - {b} = {a - b}')
	print(f'{a} * {b} = {a * b}')
	print(f'{a} / {b} = {a / b}')


if __name__ == '__main__':
	main()