4 ms·
One possible issue with this approach is that you may need to add methods in the future to the tuple. For example, the following pattern would improve code rea
by svisser 11y ago
One possible issue with this approach is that you may need to add methods in the future to the tuple.
For example, the following pattern would improve code readability as well (by making values available as attributes) but also allows you to extend it in the future when you need to add additional methods to your object:
class Person(object):
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
Example: p = Person(name="John", age=30, weight=78) and p.age for access. When needed you can add methods to this class while still keeping the code readable.
- chubot 11y agoIf you're going to do that, might as well just spell out the members, although it's verbose. What you're doing doesn't check that the attributes are valid.
- raverbashing 11y agoless readable, but you only need: self.__dict__.update(kwargs)
- detaro 11y agoThen you can replace the namedtuple with a custom class in the future.
- orangecat 11y agoYou can inherit from a namedtuple: class Person(namedtuple('Person', 'age weight height')): def is_adult(self): return self.age >= 18
- js2 11y agoI would probably even annotate that method with @property. :-)
- js2 11y agoYou can subclass namedtuple: class Foo(namedtuple("Foo", "a b c")): __slots__ = () def abc(self): return self.a + self.b + self.c