1

四个向量

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=0,y=0,z=0):
        self.a=(ct,x,y,z)
        self.r=(ct,r=[x,y,z])

P0 = FourVector()
print P0.a

P1 = FourVector(ct=9,x=1,y=2,z=4)
print P1.a

P2 = FourVector(ct=99.9,r=[1,2,4])

我的代码可以正常工作P0P1但不能正常工作P2:(有人能发现我的错误吗?

4

3 回答 3

2

r甚至不在参数列表中,为什么?只需添加它:

def __init__(self,ct=0,x=0,y=0,z=0, r=None)
于 2013-11-13T02:08:49.213 回答
2

您的方法中没有r参数__init__

class FourVector:
    def __init__(self, ct = 0, x = 0, y = 0, z = 0, r = None):
        self.a = (ct, x, y, z)
        if r is not None:
            self.a = (ct, r[0], r[1], r[2])

P0 = FourVector()
print P0.a

P1 = FourVector(ct = 9, x = 1, y = 2, z = 4)
print P1.a

P2 = FourVector(ct = 99.9, r = [1, 2, 4])
print P2.a
于 2013-11-13T02:09:23.250 回答
1
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=0, y=0, z=0, r=[]):
        self.ct = ct
        self.r =  np.array(r if r else [x,y,z])


P0 = FourVector()
print P0.r

P1 = FourVector(ct = 9, x = 1, y = 2, z = 4)
print P1.r

P2 = FourVector(ct = 99.9, r = [1, 2, 4])
print P2.r
于 2013-11-13T02:19:47.367 回答