簡體   English   中英

通過 Python 中的 class 方法訪問局部變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM