gpt4 book ai didi

python - 带有 required_arg、*args、**kwargs 的类定义

转载 作者:行者123 更新时间:2023-12-01 04:35:04 25 4
gpt4 key购买 nike

除了 *args、**kwargs 之外,我还想在来自另一个类的类中使用一个 required_arg。但目前我没有成功!这段代码:

class PageNumCanvas(canvas.Canvas):
"For add \"page number of total\" in each footer."

def __init__(self, page1, *args, **kwargs):
"Constructor."
self.page1 = page1 - 1
canvas.Canvas.__init__(self, *args, **kwargs)
self.pages = []

当我这样做时出现错误消息:canvasmaker = PageNumCanvas(1):

canvas.Canvas.__init__(self, *args, **kwargs)
TypeError: __init__() takes at least 2 arguments (1 given)

如何使用 page1 参数调用 PageNumCanvas 类?

更新#1:

如果我不在类的 init 中使用参数,我就没有问题。例如:

>>> from reportlab.pdfgen import canvas
>>> class PageNumCanvas(canvas.Canvas):
... "For add \"page number of total\" in each footer."
... def __init__(self, *args, **kwargs):
... canvas.Canvas.__init__(self, *args, **kwargs)
... self.pages = []
...
>>> canvasmaker = PageNumCanvas(1)
>>> canvasmaker
<__main__.PageNumCanvas instance at 0x7f618195df38>
>>>

更新#2:感谢goncalopp提供的方法,正确的代码是:

class PageNumCanvas(canvas.Canvas):
... "For add \"page number of total\" in each footer."
... def __init__(self, page1, *args, **kwargs):
... "Constructor."
... canvas.Canvas.__init__(self, page1, *args, **kwargs)
... self.page1 = page1 - 1
... self.pages = []
... print self.page1
...
>>> canvasmaker = PageNumCanvas(12)
11
>>>

最佳答案

您可能正在寻找

canvas.Canvas.__init__(self, page1, *args, **kwargs)

关于python - 带有 required_arg、*args、**kwargs 的类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31854169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com