Найти - Пользователи
Полная версия: Сочетание разных классов в dunder'ах
Начало » Python для новичков » Сочетание разных классов в dunder'ах
1
Alex9912
 class Vector:
	def __init__(self, x=0, y=0):
		self.x = x
		self.y = y
		pass
	def __repr__(self):
		return '({}; {})'.format(self.x, self.y)
	def __add__(self, other):
		return Vector(self.x + other.x, self.y + other.y)
	def __sub__(self, other):
		return Vector(self.x - other.x, self.y - other.y)
	def __mul__(self, other):
		if isinstance(other, int) or isinstance(other, float):
			return Vector(other * self.x, other * self.y)
		elif isinstance(other, Vector):
			return self.x * other.x + self.y * other.y
	def mult(self, other):
		return Vector(other * self.x, other * self.y)
	def __abs__(self):
		return hypot(self.x, self.y)

здравствуйте! пробую создать класс вектор, и столкнулся с такой проблемой как умножение вектора на число. я понимаю почему эта проблема присутствует. несоответствие классов. но вопрос. можно ли как-то эту проблему решить именно в __mul__? или просто довольствоваться методами класса?
py.user.next
Alex9912
разных классов в dunder'ах
В каких “dunder'ах” ?

Alex9912
я понимаю почему эта проблема присутствует
Какая проблема?

Вектор можно умножить на число, на вектор скалярно и на вектор векторно. Что у тебя в __mul__() записано, уже умножает вектор на число или на вектор скалярно. Зачем ты добавил mult(), непонятно.
Alex9912
я о том, что вектор на число не умножается

TypeError: unsupported operand type(s) for *: ‘int’ and ‘Vector’

я об этом
py.user.next
  
>>> class Vector:
...     def __init__(self, x=0, y=0):
...         self.x = x
...         self.y = y
...     def __repr__(self):
...         return '({}; {})'.format(self.x, self.y)
...     def __add__(self, other):
...         return Vector(self.x + other.x, self.y + other.y)
...     def __sub__(self, other):
...         return Vector(self.x - other.x, self.y - other.y)
...     def __mul__(self, other):
...         if isinstance(other, (int, float)):
...             return Vector(other * self.x, other * self.y)
...         elif isinstance(other, Vector):
...             return self.x * other.x + self.y * other.y
...         else:
...             raise ValueError('unknown type: {}'.format(type(other)))
...     def __rmul__(self, other):
...         if isinstance(other, (int, float)):
...             return Vector(other * self.x, other * self.y)
...         elif isinstance(other, Vector):
...             return self.x * other.x + self.y * other.y
...         else:
...             raise ValueError('unknown type: {}'.format(type(other)))
...     def __abs__(self):
...         return (self.x ** 2 + self.y ** 2) ** 0.5
... 
>>> v1 = Vector(1, 2)
>>> v2 = Vector(3, 4)
>>> 
>>> v1 + v2
(4; 6)
>>> 
>>> v1 - v2
(-2; -2)
>>> 
>>> v1 * 2
(2; 4)
>>> 
>>> 2 * v1
(2; 4)
>>> 
>>> v1 * v2
11
>>> 
>>> abs(v1)
2.23606797749979
>>>
Alex9912
спасибо!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB