Reputation: 759
I'm trying to make a class with a variable parameter list, the code:
Vector.py class code:
class Vector(tuple):
def __new__(cls, *V):
return tuple.__new__(cls, V)
def __init__(self, *V):
self.V = V
def __repr__(self):
"""An overloaded method that it writes a vector in a terminal."""
return('({})'.format(self))
TestVector.py code:
from Vector import Vector
def main():
'We create 2 Vectors'
V1 = Vector((3, 2))
V2 = Vector((4, 5))
print(V1)
print(V2)
When I execute the code I obtain none error message, only a white line.
Thanks
Upvotes: 0
Views: 80
Reputation: 7842
So there appears to be some confusion with the way you are specifying your arguments.
You use:
def __init__(self, *V):
which implies (along with the title of your question) that you want to give a variable number of arguments, like:
V1 = Vector(3, 2)
V2 = Vector(1,2,3,4,5,6,7)
yet you are passing tuples to the Vector class like:
V1 = Vector((3, 2))
V2 = Vector((1,2,3,4,5,6,7))
This is not a variable parameter list, it is just one argument regardless of how long the tuple is.
As has been pointed out in the comments above, your overloaded __repr__
method is broken and will cause the code to infinitely recurse. There is no need to overload this method as the default one does exactly what you are asking.
Putting that all together, your code becomes:
class Vector(tuple):
def __new__(cls, *V):
return tuple.__new__(cls, V)
def __init__(self, *V):
self.V = V
def main():
'We create 2 Vectors'
V1 = Vector(3, 2)
V2 = Vector(4, 5)
print(V1)
print(V2)
main()
The only question that remains is why you would want to do this all in a subclass of tuple, rather than using (for instance) numpy.
Upvotes: 1