Python在一个循环上有多个实例

2024-09-29 05:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的类来生成随机的简单PDF

from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import letter
import random
import string
import os

BOOTH_NAME = [
        'Distrito', 'Sector', 'Residencia', 'Fraccionamiento',
        'Privado', 'Ciudad', 'Colonia', 'Departamentos',
        'Recinto', 'Barrio', 'Comuna', 'Vecindad'
    ]
BOOTH_CODE = list(string.ascii_uppercase)
ZONE_CODE = ['NORTE', 'OESTE', 'SUR', 'ESTE', 'SUROESTE', 'NOROESTE', 'SURESTE', 'NORESTE']
CONCEPT_NAME = ['COMPRA/VENTA', 'TESTIMONIO', 'ESCRITURAS']
WIDTH, HEIGHT = letter
DIR_NAME = '/Users/gmwill934/PycharmProjects/notarIA/pdfs/'

class PDF(object):
    def __init__(
            self,
            casilla=str(BOOTH_NAME[random.randint(0, len(BOOTH_NAME) - 1)]),
            clave_casilla=str(BOOTH_CODE[random.randint(0, len(BOOTH_CODE) - 1)]),
            zona=str(ZONE_CODE[random.randint(0, len(ZONE_CODE) - 1)]),
            concepto=str(CONCEPT_NAME[random.randint(0, len(CONCEPT_NAME) - 1)])
    ):
        self.casilla = casilla
        self.clave_casilla = clave_casilla
        self.zona = zona
        self.concepto = concepto
        self.name = '{} {} {}'.format(self.casilla, self.clave_casilla, self.zona)
        self.save_name = os.path.join(PDF.DIR_NAME, self.name+'.pdf')

    def create_pdf(self):
        pdf = Canvas(self.save_name, pagesize=letter)
        pdf.setTitle(self.name)
        pdf.grid([10, PDF.WIDTH - 10], [10, PDF.HEIGHT - 10])
        pdf.drawString(20, PDF.HEIGHT - 30, 'Numero de Casilla:')
        pdf.drawString(130, PDF.HEIGHT - 30, str(random.randint(1000, 9999)))
        pdf.drawString(20, PDF.HEIGHT - 50, 'Nombre de Casilla:')
        pdf.drawString(130, PDF.HEIGHT - 50, self.name)
        pdf.drawString(20, PDF.HEIGHT - 70, 'Numero de Votos:')
        pdf.drawString(130, PDF.HEIGHT - 70, str(random.randint(100000, 999999)))
        pdf.drawString(20, PDF.HEIGHT - 90, 'Concepto:')
        pdf.drawString(130, PDF.HEIGHT - 90, str(self.concepto))
        pdf.showPage()
        pdf.save()

基本上,create_pdf方法使用随机值创建pdf

接下来我要做的是创建PDF class的多个实例,一次创建多个PDF

from src.pdf import PDF
# instantiate PDF class
# create multiple instances
pdf = PDF()
for n in range(10):
    pdf.create_pdf()

我也试过这个

from src.pdf import PDF
# instantiate PDF class
# create multiple instances
for n in range(10):
    pdf = PDF()
    pdf.create_pdf()

问题是,它只创建了1个PDF文件,而我预期是10个。它似乎是在1个PDF创建之后完成的

有人能对此提出建议吗?我错过什么了吗


Tags: nameimportselfpdfcreatecoderandomheight
1条回答
网友
1楼 · 发布于 2024-09-29 05:21:47

定义函数(方法)时计算的参数的默认值
因此,您的随机生成逻辑只运行一次。
你应该做:

    def __init__(
            self,
            casilla=None,
            ...
    ):
        self.casilla = (
            casilla if casilla is not None else
            str(BOOTH_NAME[random.randint(0, len(BOOTH_NAME) - 1)]))
        ...

参考:https://docs.python.org/3/reference/compound_stmts.html#function-definitions

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

相关问题 更多 >