pythonclassoop

Alternative to class objects in Python


I have code like

class abc:
    def __init__(self):
        self.a = 0
        self.b = 0
        self.c = 0

I am making array of objects of this class as below:

objs = np.array([ abc() for x in range(10)])

Is there any data structure similar to classes which can hold values a, b, c as in class abc. Also I could make array of that data structure as done above in objs object.


Solution

  • If you're using Python 3.3+, you 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 to make a custom type.

    >>> from collections import namedtuple
    >>>
    >>> abc = namedtuple('abc', 'a b c')
    >>> abc(a=0, b=0, c=0)
    abc(a=0, b=0, c=0)
    

    But it does 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