I have the following code:
from collections import namedtuple
Test = namedtuple('Test', ['number_A', 'number_B'])
test_1 = Test(number_A=1, number_B=2)
test_2 = Test(number_A=3, number_B=4)
test_3 = Test(number_A=5, number_B=6)
My question is how can I print all namedtuples, for example:
print (Test.number_A)
I want to see somthing like this as a result:
1
3
5
any ideas? thanks..
Martijn Peters advises in the comments:
Do not use numbered variables. Use a list to store all the named tuples instead. Simply loop over the list to print all contained named tuples.
Here is what that looks like:
Test = namedtuple('Test', ['number_A', 'number_B'])
tests = []
tests.append(Test(number_A=1, number_B=2))
tests.append(Test(number_A=3, number_B=4))
tests.append(Test(number_A=5, number_B=6))
for test in tests:
print test.number_A
Gives:
1
3
5
You could drive a subclass that kept track of its instances:
from collections import namedtuple
_Test = namedtuple('_Test', ['number_A', 'number_B'])
class Test(_Test):
_instances = []
def __init__(self, *args, **kwargs):
self._instances.append(self)
def __del__(self):
self._instances.remove(self)
@classmethod
def all_instances(cls, attribute):
for inst in cls._instances:
yield getattr(inst, attribute)
test_1 = Test(number_A=1, number_B=2)
test_2 = Test(number_A=3, number_B=4)
test_3 = Test(number_A=5, number_B=6)
for value in Test.all_instances('number_A'):
print value
Output:
1
3
5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With