PROGRAMMING

  MINTE9
REMEMBERS




Normal Class

p338 ! 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 Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

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

p = Point(1, 2)

assert p.x == 1
assert p.y == 2


# Named tuples

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

nt = Point(3, 4)

assert nt.x == 3
assert nt.y == 4

Drawback

p340 ! The drawback is that simple classes don't always stay simple.
 
# Named tuples drawback ...
#
# Simple classes don't always stay simple.
# You might need to add more methods

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

p = Point(1, 2)
assert p.x == 1
assert p.y == 2


# To add more methods ...
# you need to inherit the named tuple

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

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

p = Point_new(Point(1, 2))
assert p.x == 1
assert p.y == 2

Questions     github Goodies
Modules
        A B C D E F
🔔
1/2