Open main menu

Gramps β

Changes

Учебник по написанию отчетов

1,902 bytes added, 10:26, 26 November 2025
Класс Report: Translated into Russian
==Определение классов==
===Класс Report===The user's Пользовательский класс отчета должен наследовать от класса Report находящемся в модуле <code>gramps.gen.plug.report class should inherit from the Report class contained within the Report module</code>. The constructor should take three arguments Конструктор должен принимать три аргумента (besides class instance itselfне считая ссылки на текущий экземпляр класса, usually denoted by обычно называемый 'self' name): * экземпляр базы данных Gramps database instance* options class instanceэкземпляр класса параметров * user class instanceэкземпляр класса пользователя The first is the database to work withПервый аргумент - это база данных для работы. The second is the instance of the options class defined in the same reportВторой аргумент - это экземпляр класса параметров отчета, определенный вместе с самим отчетом, see next sectionкак описано в следующем разделе. The third is an instance of the Третий аргумент - это экземпляр класса User class, used for interaction with the userиспользуемый для интерактивного взаимодействия с пользователем. Here's an example of a report class definitionНиже приведен пример определения класса отчета
<pre>
from ReportBase gramps.gen.plug.report import Report, ReportUtils, ReportOptions
class ReportClassName(Report):
Report.__init__(self, database, options_class, user)
</pre>
The Конструктор класса Report class's constructor will initialize several variables for the user based off the passed valuesна основе переданных ему параметров инициализирует для пользователя несколько переменных. They areЭто:;self.doc : The opened document instance ready for outputЭкземпляр открытого документа, готового к выводу. This is of the type Его тип - это один из типов [https://gramps-project.org/docs/gen/gen_plug.html#module-gramps.gen.plug._docgenplugin docgen.basedoc Генераторов DocGen], and is и '''notНЕ ЯВЛЯЕТСЯ''' a normal file objectтипом обычного файла.;self.database : The Объект класса [https://www.gramps-project.org/docs/gen/gen_db.html#module-gramps.gen.db.base GrampsDbBase.DbReadBase DbReadBase] database object.;self.options_class : The Объект класса [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.report._options.ReportOptions ReportOptions] class passed to the report, переданный отчету.
You'll probably need a start-person for which to write the reportВозможно Вам для начала потребуется знать человека, о котором создается отчет. This person should be obtained from the Этого человека можно получить из объекта <tt>options_class</tt> object through the используя класс [https://gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.menu._person.PersonOption PersonOption class which will default to the active person in the database], который по умолчанию вернет активное лицо в базе данных. Anything else the report class needs in order to produce the report should be obtained from the Вообще говоря всё, что классу Report требуется для создания отчёта, должно быть получено из объекта <tt>options_class</tt> object. For example Например, Вы можете добавить код в конструктор класса Report для получения параметров, you may need to include the additional code in the report class constructor to obtain any options you defined for the reportкоторые Вы задали для отчета.
Report class Пользовательский класс отчета ''должен'must''' provide a содержать метод <tt>write_report()</tt> method. This method should dump the report's contents into the already opened document instanceЭтот метод выводит содержимое отчета в экземпляр открытого документа.
<pre>
def write_report(self):
self.doc.end_paragraph()
</pre>
The rest of the report class is pretty much up to the report writerВсе остальное в пользовательском классе отчета - на усмотрение разработчика. Depending on the goals and the scope of the reportОн может содержать произвольное количество кода, there can be any amount of code involvedзависящее только от целей и охвата отчёта. When the user generates the report in any modeКогда конечный пользователь будет запускать отчёт, the class constructor will be runв независимости от режима запуска сначала будет выполнен конструктор, and then the а затем будет вызван метод <tt>write_report()</tt> method will be called. So if you wrote that beautiful method listing something really importantТак что если Вы написали прекрасный метод выводящий что-то действительно важное, make sure it is eventually called from within the удостоверьтесь, что он вызывается из метода <tt>write_report()</tt>. Otherwise nobody will see it unless looking at the codeВ противном случае, никто не увидит ваш метод, если только не посмотрит код класса.
===Класс Options===
64
edits