为什么我的 class 的初始化函数 运行 没有?

Why isn't my class's init function running?

在调用另一个文件时,我正在努力理解 __init __ 函数的 class。这已经被问了很多,我一定是休息日,因为我根本无法让它工作!好吧,我收回那句话.. 如果我只使用 __init __ 或者根本不使用它,它就可以工作。这可能是我遗漏的一些愚蠢和明显的东西 - 这是怎么回事 ::

文件夹结构

文件 1 - main.py

from controller import appkey , appconf
# log file gets created in here #
app_process = appkey.generate(logfile)

文件 2 - controller.__init __.py

from public import printlog

class appkey(object) :
    def __init__(self,logfile) :
        self.logfile = logfile

    def generate(self) :
        printlog.log( message = f'Generating runtime key for application instance.'
## <<<< ERROR HAPPENS HERE | AttributeError: 'str' object has no attribute 'logfile' >>>> ##
                , file = self.logfile ### <-- 
                , level = 'info' )

        try :
            <<<< stuff >>>>
            return run_ , key_
    except :
      <<<< mayday | exit >>>>

Visual Studio 在进入 controller.__init __.py 文件后将 self: 'runtime/application_logs/12072021-122743' 显示为变量,但它永远不会变成“self.logfile”。

感谢反馈。谢谢!

问题是您没有在任何地方创建 appkey 对象,您试图在 class 本身 上调用 generate (不是 class 的实例)。当您应该将 logfile 传递给构造函数时,您还将 logfile 传递给 generate 方法。

您可以将 main.py 中的代码更改为以下内容或类似内容:

# Call the constructor first to create an appkey object, named 'a'
a = appkey(logfile)
# Now call generate on it
app_process = a.generate()  

您需要先创建 class 对象,然后调用 main.py 中的 generate 方法。

from controller import appkey , appconf
# log file gets created in here #
appkey_obj = appkey(logfile)
app_process = appkey_obj.generate()

您正在设置 self.logfile 的值(即 logfile 实例变量 ) when you create the object. Since it is an instance variable, you do not need to pass it into the generate` 方法。

您收到该错误是因为当您将 logfile 传递给 generate 时,generate 中的 self 参数被设置为 logfile 字符串价值。 self也是一个实例变量,当没有传入任何其他内容时,它将引用对象本身。但是,由于您传入的是logfile,因此self设置为logfile并尝试调用(基本上)logfile.logfile(即尝试调用字符串的实例变量)。