【问题标题】:AttributeError: 'str' object has no attribute 'path'AttributeError:“str”对象没有属性“path”
【发布时间】:2021-09-25 14:21:14
【问题描述】:

我是 python 新手,遇到了这个我无法理解的问题

AttributeError: 'str' object has no attribute 'path'
class extractor:
    """This class will find the path for the pdx"""

    def __init__(self, pdx_name,path):
        self.pdx_name = pdx_name
        self.path = path

    def __str__(self):
        return self.pdx_name

    def find_folder(self):
       if os.path.exists(self.path):
           return self.path

也许有人可以解释发生了什么,我认为这很简单,我仍然没有理解。

谢谢!f

【问题讨论】:

  • 这些形式的函数属于一个类——不是独立的。那是你的错误。
  • 你是如何使用你的提取器类的?我认为您至少需要添加一个代码 sn-p 来显示其用途。你的错误是什么时候发生的?

标签: python python-3.x function class methods


【解决方案1】:

正如@dawg 提到的,这些方法属于一个类:

import os

class File
    def __init__(self, pdx_name, path):
        self.pdx_name = pdx_name
        self.path = path

    def __str__(self):
        return self.pdx_name

    def find_folder(self):
       if os.path.exists(self.path):
           return self.path


file = File('some_name', '/Users/bob')
print(file.find_folder())

【讨论】:

  • 我认为他已经将这些方法放入 extractor 类中,但 smh 未能将它们放入代码示例中
  • @RustamGarayev,啊,这会让每个人都感到困惑:)
【解决方案2】:

in the project i have a main program and one that contain the class and i call the class in the main program if this helps

这是我调用类的主要 python 文件中的代码

导入路径为pt

val = input("Introduceti numele PDX-ului: ")
path='x'
x=pt.extractor(val,path)
print(x)
y = pt.extractor.find_folder(path)
print(y)

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2021-10-04
    • 2019-12-02
    • 2013-09-22
    • 2018-09-19
    相关资源
    最近更新 更多