class Vector:
def __init__(x,y):
self.x=x
self.y=y
How can I get two variables x,y=Vector(20,10)
?
Answer should be x=20, y=10.
If you just want to access the x
and y
attribute, you can access them using the dot notation:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
vector = Vector(10, 20)
x = vector.x
y = vector.y
print('x =', x)
print('y =', y)
# Output
x = 10
y = 20
If you want to give your class a behavior similar to tuple unpacking, you can override __iter__
:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __iter__(self):
yield self.x
yield self.y
def __str__(self):
return 'x={}, y={}'.format(self.x, self.y)
vector = Vector(x=10, y=20)
print(vector)
x, y = vector
print('x =', x)
print('y =', y)
# Output
x=10, y=20
x = 10
y = 20
Your __init__
method is currently defined incorrectly; the signature should be def __init__(self, x, y)
, where the important thing to note is that the first parameter is self
.
Without defining some method to return the x
and y
values as a tuple, you wouldn't be able to extract them as x, y = Vector(10, 20)
, you would need to access the instance attributes separately, i.e.:
vector = Vector(10, 20)
x = vector.x
y = vector.y
Alternatively, you could define an extra method on the class to return a tuple and unpack that:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def coords(self):
return self.x, self.y
vector = Vector(10, 20)
x, y = vector.coords()
print(x, y)
Output:
10 20