Python - multiple instances on a loop

gm_will :

I have the following class to generate random simple PDF's.

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()

Basically the create_pdf method creates PDF's with random values.

What I want to do next, is create multiple instances of the PDF class, to create multiple PDFs at once.

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

Also I've tried this.

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

The problem is that it only creates only 1 PDF file while I'm expecting 10. It seems as its finished after 1 PDF creation.

Can someone advise on this? Am I missing something?

Boseong Choi :

The default value of parameters evaluated when function(method) defined.
So your random generating logic runs only once.
You should do:

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

reference: 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21304&siteId=1
Recommended