Код: Выделить всё
from typing import NamedTuple
class Record(NamedTuple):
id: int
name: str
age: int
class NamedTupleList:
def __init__(self, data):
self._data = data
def attempt_access(self, row, column):
print(f'{self._data[row].age=}')
r = self._data[row]
print(f'{type(column)=}')
print(f'{column=}')
print(f'{r[column]=}')
data = [Record(1, 'Bob', 30),
Record(2, 'Carol', 25),
Record(3, 'Ted', 29),
Record(4, 'Alice', 28),
]
class_data = NamedTupleList(data)
print('show data')
print(f'{data[0]=}')
print(f'{type(data[0])=}')
print(f'{data[0].age=}')
print('\nshow class_data')
print(f'{type(class_data)=}')
print('\nattempt_access by index')
class_data.attempt_access(0, 2)
print('\nattempt_access by name')
class_data.attempt_access(0, Record.age) # why can't I do this?
Код: Выделить всё
data[0]=Record(id=1, name='Bob', age=30)
type(data[0])=
data[0].age=30
show class_data
type(class_data)=
attempt_access by index
self._data[row].age=30
type(column)=
column=2
r[column]=30
attempt_access by name
self._data[row].age=30
type(column)=
column=_tuplegetter(2, 'Alias for field number 2')
print(f'{r[column]=}')
~^^^^^^^^
TypeError: tuple indices must be integers or slices, not _collections._tuplegetter
Подробнее здесь: https://stackoverflow.com/questions/784 ... g-a-string