繁体   English   中英

class对象没有属性怎么解决

[英]How to solve class objecto has no atribute

初学者 Python 用户在这里。 所以,我试图制作一个程序来订购我的(许多)下载文件夹的文件。

我做了一个 class object 来处理许多文件夹:

class cContenedora:
def __int__(self, nCarp, dCarp): #nCarp Stands is the file name and dCarp Stands for file directory. 
    self.nCarp = nCarp
    self.dCarp = dCarp

所以,你写了一个这样的实例:

Download = cContenedora()
Download.nCarp = "Downloads/" 
#The side bar is for making a path to move my archives from with  shutil.move(path, dest)
Download.dCarp = "/Users/MyName/Download/" 
#This is for searching the folder with os.listdir(Something.dCarp)

然后,我写了我的 function,它是这样的:

def ordenador(carpetaContenedora, formato, directorioFinal): #carpetaContenedora is a Download Folder

    carpetaContenedora = cContenedora() #carpetaContenedora one of the class objects
    dirCCont = os.listdir(carpetaContenedora.dCarp) #The to directory is carpetaContenedora.cCarp
    for a in dirCCont:
        if a.endswith(formato):
            path = "/Users/Aurelio Induni/" + carpetaContenedora().nCarp + a
            try:
                shutil.move(path, directorioFinal)
                print(Fore.GREEN + a + "fue movido exitosamente.")
            except:
                print(Fore.RED + "Error con el archivo" + a)
                pass

for trys in range(len(listaCarpetasDestino)-1): #Is a list full of directories.   
    for container in listaCarpetasFuente: #A short list of all my Downloads Folder.
        for formatx in listaFormatos: #listaFormatos is a list ful of format extensions like ".pdf"
            #try: #I disabled this to see the error istead of "Error Total"
                ordenador(container, formatx, listaCarpetasDestino[trys])
            #except:
                #print(Fore.RED + "Error Total") #I disabled this to see the error.

但每次我运行它时,我都会得到以下信息:

AttributeError: 'cContenedora' object has no attribute 'dCarp'

它说错误在第 47 行(带有 os.listdir(carpetaContenedora.dCarp) 的那个)

我确定是小东西。 Python 太神奇了,但不知道出了什么问题也可能令人沮丧。

您的实例初始化时存在拼写错误。 它应该是“ init ”而不是“ int ”。

在 class cContenedora中,function 应该是

class cContenedora:
       def __init__(self, nCarp, dCarp): 
           self.nCarp = nCarp
           self.dCarp = dCarp

此外,当您传入参数时。 确保在 Value 行中传入两个参数。

CContenedora(nCarp="something",dCarp="something")

您的 class 初始值设定项,即__init__() function 有 2 个参数nCarpdCarp ,但是当您实际创建 object 时,没有传递任何参数。

您的 function ordenador将第一个参数作为carpetaContenedora ,在第一行为同一变量分配了一个新的 object 的cContenedora ,在此行,您传递的原始值将永远丢失。

这可能是它给出错误的原因。 有关如何创建类和实例化 object 的更多详细信息,请参阅此链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM