minte9
LearnRemember / PYTHON



Normal Class

When you define a class you must type a lot of code.
 
"""Named tuples
When you define a class you must type a lot of code
Python provides a more concise way with named tuples
"""

class A:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return '(%g, %g)' % (self.x, self.y)

from collections import namedtuple
B = namedtuple('B', ['x', 'y'])

a = A(1, 2)
b = B(1, 2)

assert a.x == 1 == b.x
assert a.y == 2 == b.y

print('Tests passed')

Drawback

The drawback is that simple classes don't always stay simple.
 
"""Named tuples drawback
Simple classes don't always stay simple
To add more methods you need to inherit the named tuple
"""

from collections import namedtuple
A = namedtuple('A', ['x', 'y'])

class B():
    def __init__(self, p):
        self.p = p
        self.x = p.x
        self.y = p.y

    def __str__(self):
        return 'B(%g, %g)' % (self.x, self.y)

a = A(1, 2)
b = B(A(1, 2))

assert a.x == 1 == b.x
assert a.y == 2 == b.y

print('Tests passed')






Questions and answers




Named tuples are used to write:

  • a) more concise class definition
  • b) more efficient lists

The drawback of named tuples is that:

  • a) you must inherit from it when adding methods
  • b) it cannot be overriden


References