【问题标题】:How to fix the constructor in python如何修复python中的构造函数
【发布时间】:2019-07-28 14:16:46
【问题描述】:

我知道在 python 中方法有参数 self 隐式调用,在我的代码中我无法访问我的类的构造函数。

class SmartFolder:

def _init_(self,path):
    self.path = path


path = "./temp/"
smart_folder = SmartFolder(path)
smart_folder.run()

错误:

Traceback (most recent call last):
File "smart_folder.py", line 57, in <module>
smart_folder = SmartFolder(path)
TypeError: SmartFolder() takes no arguments

但我有一个带参数的构造函数。

【问题讨论】:

  • 你确定缩进是正确的吗?
  • 这是 _ _ init _ _ 不是 _ init _(双下划线)
  • 它正在调用不带参数的默认构造函数。由于您的构造函数与@Francky_V 指出的正确构造函数名称不匹配,因此您定义的构造函数将作为普通函数而不是构造函数运行。
  • 我认为@Francky_V 想说的是,您需要使用__init__,并在单词init 之前和之后使用两个下划线。
  • @LazyCoder 绝对

标签: python class python-3.7


【解决方案1】:

请检查缩进和代码格式。希望这会有所帮助。

class SmartFolder:
    def __init__(self,path):
        self.path = path

    def run(self):
        #Your code here
        pass

path = "./temp/"
smart_folder = SmartFolder(path)
smart_folder.run()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多