List () takes at most 1 argument (3)

I want to get a vector: v:[1.0, 2.0, 3.0]

Here is my code:

 class VECTOR(list) : def _init_ (self,x=0.0,y=0.0,z=0.0,vec=[]) : list._init_(self,[float(x),float(y),float(z)]) if vec : for i in [0,1,2] : self[i] = vec[i] 

But when I typed: a = VECTOR(1,2,3) it went wrong:

TypeError: list () accepts no more than 1 argument (3 data)

How can i dissolve it?

+8
python
source share
2 answers

The problem is that you mistakenly wrote the name of the constructor. Replace _init_ with __init__ .

Here's the fixed code:

 class VECTOR(list) : def __init__ (self,x=0.0,y=0.0,z=0.0,vec=[]) : list.__init__(self,[float(x),float(y),float(z)]) if vec : for i in [0,1,2] : self[i] = vec[i] a = VECTOR(1,2,3) print(a) 

And a demonstration that it works:

  % python test.py [1.0, 2.0, 3.0] 

I would also like to give you some additional comments:

  • You must correct the coding style in accordance with PEP8 (for each Python developer to read the document completely);
  • you can probably do something more pythonic (thanks to Benjamin);
  • Inheritance is not the only way to do this, you can also use the attribute to store the list and determine the appropriate methods (thanks Veedrac);
  • you can also use super (see paddyg answer);

Editing Note: I have added relevant recommendations in the comments to this decision.

+23
source share

EDIT if you call with super(VECTOR, list).__init__() , you do not need to pass yourself. You also need to pass 1,2,3 as a list [1,2,3]

-2
source share

All Articles