TypeError: debug() 缺少 1 个必需的位置参数:从不同类调用方法时“msg”

san*_*san 5 python

请指出我做错了什么,我是编码新手。

1.第一个.py文件:

import logging
class Log:
    def __init__(self,msg):
        self.msg = msg

    def debug(self,msg):
        FORMAT  = "%(asctime)-15s%(message)s"
        logging.basicConfig(filemode = "w", filename="file.log", format = FORMAT, level=logging.DEBUG)
        logging.debug(self.msg)
Run Code Online (Sandbox Code Playgroud)

2.第二个.py文件

import first
first.Log.debug("I am in debug mode")
Run Code Online (Sandbox Code Playgroud)

当我运行 secondary.py 文件时,我收到错误 Logging.Log.debug("I am in debug mode")

TypeError: debug() missing 1 required positional argument: 'msg'** 
Run Code Online (Sandbox Code Playgroud)

ODi*_*lva 2

我不确定您要做什么,但第一个问题是您需要Log使用msg提供的参数初始化 的实例。您在这里所做的first.Log.debug("I am in debug mode")是调用debug的方法Log而不创建实例。

在您的debug方法中msg,参数是必需的,但从未使用过。相反,该方法将简单地尝试获取self.msg在 处定义的__init__

此代码的一种工作方式:

1. first.py file

import logging
class Log:
    def __init__(self,msg):
        self.msg = msg

    def debug(self):
        FORMAT  = "%(asctime)-15s%(message)s"
        logging.basicConfig(filemode = "w", filename="file.log", format = FORMAT, level=logging.DEBUG)
        logging.debug(self.msg)

2. second.py file

import first
# Note that Log is initialized with the msg you want, and only then we call debug()
first.Log("I am in debug mode").debug()
Run Code Online (Sandbox Code Playgroud)