Передать переменную в таблицу2?

Пытаясь следовать принципу DRY для python, я пытаюсь определить некоторую информацию о столбце в tables2 с помощью переменной. Я вижу, что переменная передается в мою функцию init, но я не вижу ее в основном тексте моего класса. Есть ли лучший способ сделать это? Ниже приведена упрощенная версия таблицы, которую я пытаюсь использовать.

class StuffTable(tables.Table):
  input(self.FontClass) # the variable is not showing up here
  columnAttributes = {"style": "font-size: 12px; max-width:120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"}
  columnHeaderAttributes = {"class": f"mb3 { self.FontClass }"}
  columnFooterAttributes = {"style": "font-size: 12px; font-weight: bold; max-width:120px; overflow: hidden; text-overflow: ellipsis;"}
  Type = tables.Column(verbose_name="", attrs={"th": columnHeaderAttributes, "td": columnAttributes})
  TypeDescription = tables.Column(verbose_name="Type", attrs={"th": columnHeaderAttributes, "td": columnAttributes})
  Column3= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes})
  Column4= tables.Column(attrs={"th": columnHeaderAttributes, "td": columnAttributes})

  def __init__(self, *args, **kwargs):
      temp_fontclass = kwargs.pop("FontClass")
      super(StuffTable, self).__init__(*args, **kwargs)
      self.FontClass = temp_fontclass
      input(self.FontClass) # this does show that the variable is being passed

Здесь не отображается:

class StuffTable(tables.Table):
  input(self.FontClass) # the variable is not showing up here
  columnAttributes = {"style": "font-size: 12px; max-width:120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"}
  ...

В теле class определяются переменные класса, которые копируются как переменные экземпляра в __init__. Экземпляр tables2 должен иметь self.FontClass после инстанцирования, любезно предоставленный вашим init. Попробуйте сделать это в оболочке.

>>> foo = StuffTable( FontClass='bar', whatever_keeps_it_happy)
>>> foo.FontClass

должен показывать "bar". Вы можете определить значение по умолчанию FontClass = 'default' в теле вашего класса, и использовать kwargs.pop('FontClass', None), чтобы сделать его необязательным во время инстанцирования.

Вернуться на верх