Total Pageviews

2018/04/06

[Python] namedtuple

Assume I create a Dog class as bellows:
class Dog():
    def __init__(self, size, name):
        self.size = size
        self.name = name

If I would like to set values into Dog class, the code snippet looks like:
pug = Dog('小型犬', '巴哥犬')
shiba = Dog('中型犬', '柴犬')
print('size = {}, name = {}'.format(pug.size, pug.name))
print('size = {}, name = {}'.format(shiba.size, shiba.name))


We can use namedtuple instead of Class.The code snippet are the following:
from collections import namedtuple
# namedtuple instances are just as memory efficient as regular tuples 
# because they do not have per-instance dictionaries. 
# Each kind of namedtuple is represented by its own class, 
# created by using the namedtuple() factory function. 
# The arguments are the name of the new class and a string containing the names of the elements.
Dog = namedtuple('Dog', 'size name')
corgi = Dog('小型犬', '柯基')
husky = Dog('中型犬', '哈士奇')
print('size = {}, name = {}'.format(corgi.size, corgi.name))
print('size = {}, name = {}'.format(husky.size, husky.name))

No comments: