[英]Access a local variable via class method in Python
我是 Python 课程的新手,所以请帮帮我。 我正在使用 fpdf package 在 pdf 中生成报告。
我正在使用以下示例代码生成带有页脚的 PDF 页面。
https://pyfpdf.readthedocs.io/en/latest/Tutorial/index.html#header-footer-page-break-and-image
from fpdf import FPDF
class PDF(FPDF):
def header(self):
# Logo
self.image('logo_pb.png', 10, 8, 33)
# Arial bold 15
self.set_font('Arial', 'B', 15)
# Move to the right
self.cell(80)
# Title
self.cell(30, 10, 'Title', 1, 0, 'C')
# Line break
self.ln(20)
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
# Instantiation of inherited class
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
for i in range(1, 5):
pdf.cell(0, 10, 'Printing line number ' + str(i), 0, 1)
pdf.output('tuto2.pdf', 'F')
这会生成 5 页。 我想在页脚中添加一个列表元素。
list=['A','B','C','D','E']
for i in range(1, 5):
pdf.cell(0, 10, 'Printing line number ' + str(i)+list[i], 0, 1)
pdf.output('tuto2.pdf', 'F')
如何将此列表传递给 Class? 此列表在从上面的 Class 派生的 class 中生成。
我没有找到 package 进行测试,但我添加了一个 init 来生成一个字母列表,这样您就可以在基于
"""
https://stackoverflow.com/questions/61473844/access-a-local-variable-via-class-method-in-python
https://stackoverflow.com/questions/453576/is-there-a-fast-way-to-generate-a-dict-of-the-alphabet-in-python
"""
from fpdf import FPDF
import string
class PDF(FPDF):
def ___init___(self):
letters = string.ascii_lowercase
alphabet = d = dict(zip(range(1,27), letters))
def header(self):
# Logo
self.image('logo_pb.png', 10, 8, 33)
# Arial bold 15
self.set_font('Arial', 'B', 15)
# Move to the right
self.cell(80)
# Title
self.cell(30, 10, 'Title', 1, 0, 'C')
# Line break
self.ln(20)
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + str(self.alphabet.get(self.page_no()) + '/{nb}', 0, 0, 'C')
if __name__ == '__main__':
# Instantiation of inherited class
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
for i in range(1, 5):
pdf.cell(0, 10, 'Printing line number ' + str(i), 0, 1)
pdf.output('tuto2.pdf', 'F')
幸运的是,想通了!
class PDF1(FPDF,HTMLMixin):
def __init__(self, list):
super(PDF1, self).__init__()
self.proper_name = list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.