注意:此问题是一般编程问题,与Fourvector无关。
import numpy as np
class FourVector:
""" This document is a demonstration of how to create a class of Four vector """
def __init__(self, ct=0, x=1, y=5, z=2, r=None):
self.ct = ct
self.r = np.array(r if r else [x,y,z])
def __repr__(self):
return "%s(ct=%g,r=array%s)"% ("FourVector",self.ct,str(self.r))
def copy(self):
return FourVector(self.ct,self.r)
c1=FourVector(ct=0,r=[1,2,3]) # Note: c1,c2 here are objects, we used __repr__ to make them printable
print c1
c2=c1.copy() #use method copy within object c1
c2.ct=99
print c2
答案 0 :(得分:1)
复制时,您将两个未命名的参数传递给FourVector.__init__
。 Python在位置上解释它们,因此您实际上是在调用它们:
FourVector.__init__(new_self, ct=self.ct, x=self.r, y=5, z=2, r=None)
r
仍为None
,因此new_self.r
被指定为np.array([self.r, y, z])
。这就是c2
中的数组有额外条款的原因。
相反,您需要告诉Python第二个值应该是r
参数,而不仅仅是第二个参数:
def copy(self):
return FourVector(self.ct, r=self.r)
或者,您可以重新排序参数:
def __init__(self, ct, r=None, x=1, y=5, z=2):
甚至删除x
,y
和z
个参数,并将其作为r
的默认值提供:
def __init__(self, ct, r=[1,5,2]):