PROGRAMMING

m9/ PYTHON
REMEMBERS




Named Tuple

p338 ! When you define a class you must type a lot of code.
 
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)
print(p) # (1, 2)
... 2 lines
 
Python provides a more concise way with named tuples.
 
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])

p = Point(1, 2)
print(p) # Point(x=1, y=2)
p340 ! The drawback is that simple classes don't always stay simple. You might decide later to add more methods, and need to inherit.
 
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])

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

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

p = NewPoint(Point(1, 2))
print(p) # NewPoint(1, 2)
... 5 lines
 

Questions    

        A B C D E F
🔔
1/2