我希望除了* args之外还使用一个required_arg,来自另一个类的一个类中的** kwargs。但目前我没有成功! 这段代码:
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
>>>
答案 0 :(得分:1)
你可能正在寻找
canvas.Canvas.__init__(self, page1, *args, **kwargs)
答案 1 :(得分:1)
在示例here中,您需要在实例化canvas.Canvas()
时提供名称。
你的第二个版本没有给你一个错误的原因是你仍然传递1
传递给Canvas
构造函数,因为你删除了page1
参数。 / p>
为了使其有效,您只需传递一个名称和页码:
from reportlab.pdfgen import canvas
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, "Hello.pdf")
print canvasmaker.page1
<强>输出强>
0