Skip to main content
 首页 » 编程设计

Python: self 作为属性

2025年05月04日16emanlee

我的问题是:当我测试“isProduct”方法时,我收到错误消息:

TypeError: isProduct() takes exactly 2 arguments (1 given) 

所以,我查找了这个问题,发现我必须在调用我的方法之前添加“self”。我做到了。但是,它仍然说:

NameError: name 'self' is not defined 

不要介意方法说什么,我的问题涉及属性、类和 self 。 这是我的代码,我在做什么(非常)错了?

import xlrd 
wb=xlrd.open_workbook('C:\\Inputs_UNF_newForm.xlsx') 
s=wb.sheet_by_name('Chemical treatments') 
p=wb.sheet_by_name('Products') 
 
class World: 
 
 
 def RowMatrix(self,sheet_name,matrix_name): 
    sheet=wb.sheet_by_name(sheet_name) 
    number_of_rows = sheet.nrows 
 
    for row in range(number_of_rows): 
        value  = str((sheet.cell(row,0).value)) 
 
        if value == "#" +matrix_name: 
            start=row 
 
        if value !="": 
            end=row+1 
 
    return (start,end) 
 
 
 def isProduct(self,look_for): 
 
    (start,end)= World.RowMatrix("Products","Products") 
    number_of_columns=p.ncols 
 
    for row in range(start,end): 
        for col in range(number_of_columns): 
            value  = str((sheet.cell(row,col).value)) 
            if value == look_for: 
                return true 
            else: 
                return false 
 
 
 if self.isProduct("K20"): 
    print("true") 
 else: 
    print("false") 

请您参考如下方法:

正如其他人所指出的,您需要创建一个 World 类的实例,以便在类之外访问它。在类中,您通常应该通过 self 访问它,而不是通过类名。所以

(start,end)= World.RowMatrix("Products","Products") 

应该是

start, end = self.RowMatrix("Products", "Products") 

但是 isProduct() 方法可能不会执行您想要的操作,因为它会在处理完第一行的第一列后返回。

在 Python 中,使用 __init__() 方法初始化一个类(必要时)是很正常的。这在官方 Python 文档中有解释 tutorial以及 André Laszlo 在对您的问题的评论中链接的教程。


而不是做

if value == look_for: 
    return True 
else: 
    return False 

简单地做

return value == look_for 

我之前没有提到这个,因为我怀疑 isProduct() 中的逻辑是错误的,因为 return 语句意味着该方法会跳出那些嵌套的 for 循环在它测试第一个 value 之后。