具有getter和setter的Python属性

时间:2016-11-19 17:32:14

标签: python oop

我是Python新手。

我想要一个名为“Verbosity”的课程。它用于控制我的新Python程序的打印输出量。

在我的程序运行时,详细程度应该是常量,因此我打算用所需详细程度的级别初始化Verbosity对象。让我们调用这个对象的实例“动词”。

当我的程序运行时,我经常想检查详细程度,以便程序知道何时打印输出。因此,我想调用verb.high,verb.low等,然后返回true或false。

以下是一些示例代码(基于我找到的某些软件包中的一些代码),但它在我的程序中仍然无效:

VERB_QUIET = 0
VERB_LOW = 1
VERB_MEDIUM = 2
VERB_HIGH = 3
VERB_DEBUG = 4

class Verbosity(object):
    """Class used to determine what to print to standard output.

    Attributes:
       level: Determines what level of output to print.
    """
    value = "low"

    def __init__(self, new_value="low"):

        self.level = new_value

    def __getattr__(self, name):
        """Determines whether a certain verbosity level is
        less than or greater than the stored value.

        Args:
           name: The verbosity level at which the info/warning string
              will be output.
        """

        if name is "quiet":
            return self.level >= VERB_QUIET
        elif name is "low":
            return self.level >= VERB_LOW
        elif name is "medium":
            return self.level >= VERB_MEDIUM
        elif name is "high":
            return self.level >= VERB_HIGH
        elif name is "debug":
            return self.level >= VERB_DEBUG

    def __setattr__(self, name, value):
        """Sets the verbosity level

        Args:
           name: The name of what to set. Should always be 'level'.
           value: The value to set the verbosity to.

        Raises:
           ValueError: Raised if either the name or the level is not
              a valid option.
        """

        if name == "level":
            if value == "quiet":
                level = VERB_QUIET
            elif value == "low":
                level = VERB_LOW
            elif value == "medium":
                level = VERB_MEDIUM
            elif value == "high":
                level = VERB_HIGH
            elif value == "debug":
                level = VERB_DEBUG
            else:
                raise ValueError("Invalid verbosity level " + str(value) + " specified.")
            super(Verbosity, self).__setattr__("level", level)

如果你有更好的方法,我会很高兴听到这个。我仍然对如何使上述方法有效感兴趣。

2 个答案:

答案 0 :(得分:0)

请参阅Python内置logging模块。没有必要重新发明轮子。

以下是文档中的示例:

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything

如果要设置日志记录级别以便打印INFO +更高优先级的消息:

logging.getLogger().setLevel(logging.INFO)

我还建议坚持使用此处列出的默认日志记录级别:

  

enter image description here

答案 1 :(得分:0)

在尝试按照jonrsharpe的要求创建更好的示例代码时,令我惊讶的是我从上面得到了代码。但我仍然打算使用Python的日志模块...... :-)

问题主要在于我是如何尝试使用详细级别的。现在在下面的代码中包含了如何使用它。 (我不知道我之前做了什么,我改变了很多代码......)

class Simulation(object):

    def __init__(self, verbosity_level="low"):

        self.verbosity = Verbosity(verbosity_level)


VERB_QUIET = 0
VERB_LOW = 1
VERB_MEDIUM = 2
VERB_HIGH = 3
VERB_DEBUG = 4

class Verbosity(object):
    value = "low"

    def __init__(self, verbosity_level="low"):

        self.level = verbosity_level

    def __getattr__(self, name):

        if name == "quiet":
            return self.level >= VERB_QUIET
        elif name == "low":
            return self.level >= VERB_LOW
        elif name == "medium":
            return self.level >= VERB_MEDIUM
        elif name == "high":
            return self.level >= VERB_HIGH
        elif name == "debug":
            return self.level >= VERB_DEBUG

    def __setattr__(self, name, value):

        if name == "level":
            if value == "quiet":
                level = VERB_QUIET
            elif value == "low":
                level = VERB_LOW
            elif value == "medium":
                level = VERB_MEDIUM
            elif value == "high":
                level = VERB_HIGH
            elif value == "debug":
                level = VERB_DEBUG
            else:
                raise ValueError("Invalid verbosity level " + str(value) + " specified.")
            super(Verbosity, self).__setattr__("level", level)


sim = Simulation(verbosity_level = "medium");
if sim.verbosity.high: 
    print "Simulation is starting"