i have named tuple.
import collections mynamedtuple = collections.namedtuple('mynamedtuple', 'prop1 prop2 foo bar')
i define class can initialized these named tuples.
class myclass(): def __init__(self, t): self.prop1 = t.prop1 self.prop2 = t.prop2 self.foo = t.foo self.bar = t.bar
the larger mynamedtuple
more typing have define myclass
i'm curious if there more efficient way define myclass
.
you've got couple options... namedtuple
returns class -- can subclass directly:
class myclass(mynamedtuple): ...
of course, means myclass
is tuple
might not desirable...
you can use _fields
attribute of namedtuple (it's documented -- leading underscore prevent property name collisions rather indicate "private" member)...
def __init__(self, t): field in t._fields: setattr(self, field, getattr(t, field))
of course, kind of setting via introspection isn't clear thing read either (and might cause spurious linter warnings) ...
otherwise, there isn't way make linters happy and have short code , writing them out may best option. if number of fields in namedtuple expected change @ in future, i'd advise have unit-test checks freshly created myclass
against mynamedtuple
used create make sure of properties of mynamedtuple
being set. could (and should) use introspection _fields
check.