patronus
patronus

Reputation: 103

How to get all the attributes in python for a class that inherits from a named_tuple

I have a python class that I inherit from a named tuple. I add another attribute to it's instance

from collections import namedtuple
class Test(namedtuple("Test", ('a', 'b', 'c', 'd', 'e'))):
     pass
T = Test(1,2,3,4,5)
T.list = [ 1,2,3,4,5,6,7,8]

So T has 6 attributes: a,b,c,d,e,list. Is there any way to print all the attributes using one command? "T.__dict" gives me just "list" attribute. "T.__fields" gives me all the namedtuple fields.

I don't think I fully understand what inheriting from namedtuple does.

Upvotes: 1

Views: 989

Answers (1)

Cary Shindell
Cary Shindell

Reputation: 1386

Using the dir(T) command will print all the attributes (including builtin, class attributes) of T.

from collections import namedtuple
class Test(namedtuple("Test", ('a', 'b', 'c', 'd', 'e'))):
     pass
T = Test(1,2,3,4,5)
T.list = [ 1,2,3,4,5,6,7,8]
print dir(T)

output:

['add', 'class', 'contains', 'delattr', 'dict', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'getnewargs', 'getslice', 'getstate', 'gt', 'hash', 'init', 'iter', 'le', 'len', 'lt', 'module', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'rmul', 'setattr', 'sizeof', 'slots', 'str', 'subclasshook', '_asdict', '_fields', '_make', '_replace', 'a', 'b', 'c', 'count', 'd', 'e', 'index', 'list']

Upvotes: 3

Related Questions