Advanced · Classes · 194 of 264
Vectors
Write a Vector class for 2D vectors with + (addition), a dot product method and a length method.
Input: two vectors "x y", one per line. Output: their sum as x y, then the dot product, then the length of the sum with two decimals, each on its own line.
Examples
Input
1 2 3 4
Output
4 6 11 7.21
Input
0 0 0 0
Output
0 0 0 0.00
One more test checks other inputs when you press Check.
Stuck? The idea behind classes
A class describes a kind of object: its data (attributes, set in __init__) and what it can do (methods). Each object made from it has its own data.
self is the object a method is called on; __str__ says how the object prints.
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def pay_in(self, amount):
self.balance += amount
acc = Account("Ann")
acc.pay_in(5)
print(acc.balance)Watch for: Every method's first parameter is self, and attributes are reached through it: self.balance, not balance.