使用__init__为四个向量创建一个类

时间:2013-11-13 01:59:18

标签: python python-2.7 numpy initialization

Four Vectors

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 :(任何人都可以发现我的错误吗?

3 个答案:

答案 0 :(得分:2)

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

def __init__(self,ct=0,x=0,y=0,z=0, r=None)

答案 1 :(得分: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

答案 2 :(得分: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