user2993263
user2993263

Reputation: 55

Defining function with variables in an array in initialization of class

I have written the following,

import numpy as np
class FV:
    def __init__(self,x=0,a=0,b=0,c=0):
        r=np.array([a,b,c])
        self.t=x
        self.s=r

but it tells me that:

__init__() got an unexpected keyword argument 'r'

when I input P2 = FourVector(ct=99.9, r=[1,2,3])

Upvotes: 1

Views: 63

Answers (1)

arturomp
arturomp

Reputation: 29630

You're passing the array instead of creating it inside the function, which you seem to want to do given the line r=np.array([a,b,c]).

Assuming x is the same as ct, try P2 = FourVector(99.9,1,2,3). Otherwise, make sure you decide on whether you want to call your parameter ct or x. You pass in ct but you use x inside your function.

You also have a name issue with your class, which you declare asFV but you try to use as FourVector. Try to be a bit more careful with your names!

Given some decisions about it, your code should look like this:

import numpy as np
class FourVector:
    def __init__(self,ct=0,a=0,b=0,c=0):
        r=np.array([a,b,c])
        self.t=ct
        self.s=r

which you can then call as

P2 = FourVector(99.9,1,2,3)

Also note that since you assign r and then s=r, you can just do self.s=np.array([a,b,c]) directly, unless you have some reason to keep r around separately.

Upvotes: 2

Related Questions