0
0

More than 5 years have passed since last update.

pythonでrubyのstructがほしい時

Last updated at Posted at 2014-11-28

pythonでrubyのstructがほしい時に・・・

前提

Python 3.4.1

namedtuple

namedtuple を使うらしい

ipython
>>> from collections import namedtuple
>>> f = ('Request', 'host sc  size')
>>> Request = namedtuple('Request', 'host sc size')
>>> r = Request('10.60.111.10', 200, 456)
>>> print (r)
Request(host='10.60.111.10', sc=200, size=456)
>>> print(r.size)
456

ただし変更をしようとすると AttributeError が発生

ipython
>>> r.size = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

サンプル

ホスト名・ステータスコード・サイズを namedtuple で宣言。
.host みたいにアクセスできる。

sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from collections import namedtuple

Request = namedtuple('Request', 'host sc size')
request = Request('10.60.111.10', 200, 456)
print(request)
# stdout: Request(host='10.60.111.10', sc=200, size=456)
print(request.size)
# stdout: 456

リンク

書き換え可能なstruct

PythonでRubyのStruct風の構造体を実現する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0