Alternate to class objects in python -
i have code like
class abc: def __init__(self): self.a = 0 self.b = 0 self.c = 0
i making array of objects of class below:
objs = np.array([ abc() x in range(10)])
is there data structure similar classes can hold values a,b,c in class abc. make array of data structure done above in objs object. kindly if guide.
if you're using python 3.3+, can use types.simplenamespace
:
>>> import types >>> types.simplenamespace(a=0, b=0, c=0) namespace(a=0, b=0, c=0) >>> obj = types.simplenamespace(a=0, b=0, c=0) >>> obj.a 0 >>> obj.b 0 >>> obj.c 0
in lower version, use collections.namedtuple
make custom type.
>>> collections import namedtuple >>> >>> abc = namedtuple('abc', 'a b c') >>> abc(a=0, b=0, c=0) abc(a=0, b=0, c=0)
but not allow attribute setting unlike types.simplenamespace
:
>>> obj = abc(a=0, b=0, c=0) >>> obj.a 0 >>> obj.a = 1 traceback (most recent call last): file "<stdin>", line 1, in <module> attributeerror: can't set attribute
Comments
Post a Comment