名称错误:名称“自己”将属性作为参数传递给方法时未定义

发布于 2024-11-29 07:30:57 字数 2146 浏览 1 评论 0原文

我制作的使用 pyPdf 编辑 Pdf 的小程序遇到了一些问题。我试图将 pdf 的最后一页 (self.lastpage) 作为默认参数传递给类方法 (pageoutput) 当我这样做时,我收到以下错误:

Traceback (most recent call last):
  File "C:\Census\sf1.py", line 5, in <module>
    class PdfGet():
  File "C:\Census\sf1.py", line 35, in PdfGet
    def pageoutput(self,outfile,start_page=0,end_page=self.lastpage):
NameError: name 'self' is not defined 

如果我简单地指定一个数字作为 end_page 它可以工作,但是如果我使用属性,它会失败。这个错误对我来说是一个神秘的赌注。这似乎不是 pypdf 的问题,因为我可以毫无问题地打印 pdf 的最后一页。我将非常感谢任何有关正在发生的事情的见解!

这是我的代码(如果重要的话,我正在使用 pypdf 的 3.x 兼容版本):

from pyPdf import PdfFileWriter, PdfFileReader
import re
import time

class PdfGet():
    def __init__(self):
        self.initialize()

    def initialize(self):
        while True:
            raw_args = input('Welcome to PdfGet...\n***Please Enter Arugments (infile,outfile,start_page,end_page) OR type "quit" to exit***\n').strip() 
            if raw_args.lower() == 'quit':
                break
            print("Converting Pdf...")
            self.args = re.split(r',| ',raw_args)
            self.opener(*self.args[0:1])
            if len(self.args)== 4:
                self.pageoutput(*self.args[1:])
            elif len(self.args) == 3:
                self.pageoutput(*self.args[1:3])
            else:
                self.pageoutput(*self.args[1:2])
            print("Successfuly Converted!")
            nextiter = input('Convert Another PDF? (Type "yes" or "no")').lower()
            if nextiter == 'no':
                break

    def opener(self,infile):
        self.output = PdfFileWriter()
        self.pdf = PdfFileReader(open(infile, "rb"))
        self.pagenum = self.pdf.getNumPages()
        self.lastpage = self.pagenum+1
        print(self.lastpage)

    def pageoutput(self,outfile,start_page=0,end_page=self.lastpage):
        for i in range (int(start_page)-1,int(end_page)):
            self.output.addPage(self.pdf.getPage(i))    
        outputStream = open(outfile, "wb")
        self.output.write(outputStream)
        outputStream.close()

if __name__ == "__main__":
    PdfGet()
    time.sleep(5)

I am having some issues with a small program I have made that edits Pdfs using pyPdf. I am attempting to pass the last page of the pdf (self.lastpage) as a default parameter to a class method (pageoutput) When I do this I receive the following error:

Traceback (most recent call last):
  File "C:\Census\sf1.py", line 5, in <module>
    class PdfGet():
  File "C:\Census\sf1.py", line 35, in PdfGet
    def pageoutput(self,outfile,start_page=0,end_page=self.lastpage):
NameError: name 'self' is not defined 

If i simply specify a number as the end_page it works, yet it fails if I use an attribute. This error is a bet cryptic to me. It doesnt seem to be a problem with pypdf as I can print the lastpage of the pdf with no issues. I would greatly appreciate any insight as to what is going on!

Here is my code (I am using the 3.x compatbile version of pypdf if that matters):

from pyPdf import PdfFileWriter, PdfFileReader
import re
import time

class PdfGet():
    def __init__(self):
        self.initialize()

    def initialize(self):
        while True:
            raw_args = input('Welcome to PdfGet...\n***Please Enter Arugments (infile,outfile,start_page,end_page) OR type "quit" to exit***\n').strip() 
            if raw_args.lower() == 'quit':
                break
            print("Converting Pdf...")
            self.args = re.split(r',| ',raw_args)
            self.opener(*self.args[0:1])
            if len(self.args)== 4:
                self.pageoutput(*self.args[1:])
            elif len(self.args) == 3:
                self.pageoutput(*self.args[1:3])
            else:
                self.pageoutput(*self.args[1:2])
            print("Successfuly Converted!")
            nextiter = input('Convert Another PDF? (Type "yes" or "no")').lower()
            if nextiter == 'no':
                break

    def opener(self,infile):
        self.output = PdfFileWriter()
        self.pdf = PdfFileReader(open(infile, "rb"))
        self.pagenum = self.pdf.getNumPages()
        self.lastpage = self.pagenum+1
        print(self.lastpage)

    def pageoutput(self,outfile,start_page=0,end_page=self.lastpage):
        for i in range (int(start_page)-1,int(end_page)):
            self.output.addPage(self.pdf.getPage(i))    
        outputStream = open(outfile, "wb")
        self.output.write(outputStream)
        outputStream.close()

if __name__ == "__main__":
    PdfGet()
    time.sleep(5)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

肩上的翅膀 2024-12-06 07:30:57

您应该将默认参数传递给 None,然后在方法中自己进行分配。

def pageoutput(self, outfile, start_page=0, end_page=None):
    if end_page is None:
        end_page = self.lastpage

无法在方法声明中使用 self,因为在此阶段 self 尚未定义(加载模块时读取方法签名,调用方法时 self 在运行时可用。)

You should rather pass it a default argument to None and then in the method do the assignment yourself.

def pageoutput(self, outfile, start_page=0, end_page=None):
    if end_page is None:
        end_page = self.lastpage

It is not possible to use self in the method declaration because at this stage self is not yet defined (method signatures are read when the module is loaded, and self is available at runtime when the method is called.)

鲜肉鲜肉永远不皱 2024-12-06 07:30:57

默认参数在创建函数时计算,而不是在执行函数时计算,并且它们位于定义函数的命名空间中,而不是函数本身的命名空间中。

这会产生以下后果:
1. 不能在默认值中引用函数的其他参数——该参数的值尚不存在。
2. 使用可变值作为默认值时应该小心 - 所有对函数的调用都将收到相同的可变对象。

因此,如果您想在构造默认值时访问其他参数(例如 self)或使用新的可变对象,则应该使用 None 作为默认值,并在执行过程中分配不同的东西的函数。

Default arguments are evaluated when the function is created, not when the function is executed, and they live in the namespace where the function is being defined, not in the namespace of the function itself.

This has the following consequences:
1. You can't reference other arguments of the function in a default value – the value of this argument doesn't exist yet.
2. You should be careful when using mutable values as default values – all calls to the function would receive the same mutable object.

So, if you want to access the other arguments (such as self) or to use a fresh mutable object when constructing the default value, you should use None as the default, and assign something different during the execution of the function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文