可以有实例的类 python

问题描述 投票:0回答:1

我正在开发一个日志库。我想改变我的类,以便可以拥有它的实例。我的想法应该是这样的:

from froggius import Froggius

instance = Froggius()
instance.debug('Hello World')

我的班级和其他班级一样简单;带有一些变量的 init 函数和带有一些参数的其他函数,例如调试或警告。此时,当我运行上面的代码时,我得到以下输出:

[DBG] [03/04/2024 15:16:15] <froggius.logger.Froggius object at 0x1001eda00>

课程就这样开始了:

class Froggius():
    """
    Main class of Froggius
    Includes logging methods
    """
    
    def __init__(self, file_path=None, print_out=None) -> None:
        global glob_file_path, glob_print_out
        if file_path is not None:
            glob_file_path = file_path
        else:
            glob_file_path = None
        if print_out is not None:
            glob_print_out = print_out
        else:
            glob_print_out = None

    def debug(log_msg, file_path=None, print_out=None):
        """
        Writes logs, optionally to a file.

        Parameters
        ----------
        log_msg : str
            The message to be logged.
        file_path : str, optional
            The path to the file where the log should be saved, by default None
        highliting : bool, optional
            Whether the DEBUG tag should be highlighted with ANSI escape sequences, by default True
        print_out : bool, optional
            Whether the log should be printed to the stdout, by default True
        """
python class logging instance
1个回答
0
投票

正如其他人在评论中指出的那样,Python 中的类默认已经可以拥有实例,并且您给出的示例可以工作。

from froggius import Froggius

instance = Froggius()
instance.debug('Hello World')

接下来,您可以创建任意数量的实例,这是 W3 学校的另一个示例:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

正如您所看到的,它与您编写的内容几乎相同,因此只需为对象分配一个变量即可创建实例,如下所示:

instance1 = Froggius()
instance2 = Froggius()

等等。有关 Python 课程的更多信息,我建议您查看 W3 学校网站上的此页面

© www.soinside.com 2019 - 2024. All rights reserved.