Python - 循环中的多个实例
Python - multiple instances on a loop
我有以下 class 来生成随机的简单 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 后完成。
有人可以就此提出建议吗?我错过了什么吗?
function(method)defined.
时求值参数的默认值
所以你的随机生成逻辑只运行一次。
你应该这样做:
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
我有以下 class 来生成随机的简单 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 后完成。
有人可以就此提出建议吗?我错过了什么吗?
function(method)defined.
时求值参数的默认值
所以你的随机生成逻辑只运行一次。
你应该这样做:
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