感谢您帮助我了解此错误。我按照特定说明仔细检查了所有参数。当我运行Python 3.6时,它给我以下错误NameError:未定义名称'DEFAULT_STRING'。我检查了代码的所有部分,无法理解为什么在给我NameError时为什么我无法运行该代码。再次感谢您帮助我理解该错误。

class TripleString:

    # intended class constants

    MIN_LEN = 1
    MAX_LEN = 50
    DEFAULT_STRING = "(undefined)"


# constructor method

def __init__(self, string1 = DEFAULT_STRING, string2 = DEFAULT_STRING,
            string3 = DEFAULT_STRING):

    # assigning default values to the variables first

    self.string1 = self.DEFAULT_STRING

    self.string2 = self.DEFAULT_STRING

    self.string3 = self.DEFAULT_STRING

    # setting values using setter methods,

    self.set_string1(string1)

    self.set_string2(string2)

    self.set_string3(string3)


# mutator ("set") methods

def set_string1(self, string1):
    if self.valid_string(string1):
        self.string1 = string1

        return True

    return False


def set_string2(self, string2):
    if self.valid_string(string2):
        self.string2 = string2

        return True

    return False


def set_string3(self, string3):
    if self.valid_string(string3):
        self.string3 = string3

        return True

    return False


# accessor ("get") methods

def get_string1(self):
    return self.string1


def get_string2(self):
    return self.string2


def get_string3(self):
    return self.string3


def to_string(self):
    return self.string1 + ", " + self.string2 + ", " + self.string3


# helper methods for entire class

def valid_string(self, the_str):
    if len(the_str) >= self.MIN_LEN and len(the_str) <= self.MAX_LEN:
        return True

    return False


# ------------- CLIENT --------------------------------------------------

# Create 4 TripleString objects and printing

triple_string_num_1 = TripleString()

print(triple_string_num_1.to_string())

triple_string_num_2 = TripleString("Alice")

print(triple_string_num_2.to_string())

triple_string_num_3 = TripleString("Bob", "Chris")

print(triple_string_num_3.to_string())

triple_string_num_4 = TripleString("Oliver", "Laurel", "Thea")

print(triple_string_num_4.to_string())

print("")

# mutating values using setter methods

triple_string_num_1.set_string1("Lance")

triple_string_num_2.set_string2("XYZ")

triple_string_num_3.set_string1("Bobby")

triple_string_num_4.set_string2("Felicity")

print(triple_string_num_1.to_string())

print(triple_string_num_2.to_string())

print(triple_string_num_3.to_string())

print(triple_string_num_4.to_string())

print("")

# testing if validation working properly

if triple_string_num_4.set_string2(""):

    print("successful in setting empty string for string2 of 4th object," + \
          "validation is not working properly")

else:

    print(
        "failed in setting empty string for string2 of 4th object," + \
        "validation is working properly")

    print("Value after setting: ", triple_string_num_4.get_string2())

最佳答案

使用适当的缩进,您不应收到报告的名称错误:

class TripleString:

    MIN_LEN = 1
    MAX_LEN = 50
    DEFAULT_STRING = "(undefined)"

    def __init__(self, string1=DEFAULT_STRING, string2=DEFAULT_STRING,
                string3=DEFAULT_STRING):

        self.string1 = self.DEFAULT_STRING
        self.string2 = self.DEFAULT_STRING
        self.string3 = self.DEFAULT_STRING

        self.set_string1(string1)
        self.set_string2(string2)
        self.set_string3(string3)

    def set_string1(self, string1):
        if self.valid_string(string1):
            self.string1 = string1
            return True
        return False

    def set_string2(self, string2):
        if self.valid_string(string2):
            self.string2 = string2
            return True
        return False

    def set_string3(self, string3):
        if self.valid_string(string3):
            self.string3 = string3
            return True
        return False

    def get_string1(self):
        return self.string1

    def get_string2(self):
        return self.string2

    def get_string3(self):
        return self.string3

    def to_string(self):
        return self.string1 + ", " + self.string2 + ", " + self.string3

    def valid_string(self, the_str):
        if len(the_str) >= self.MIN_LEN and len(the_str) <= self.MAX_LEN:
            return True
        return False

可以使用属性更清晰地编写代码:
class TripleString:

    MIN_LEN = 1
    MAX_LEN = 50
    DEFAULT_STRING = "(undefined)"

    @property
    def string1(self):
        return self._string1

    @string1.setter:
    def string1(self, value):
        self._string1 = self._validate(value)

    @property
    def string2(self):
        return self._string2

    @string2.setter:
    def string2(self, value):
        self._string2 = self._validate(value)

    @property
    def string3(self):
        return self._string3

    @string3.setter:
    def string3(self, value):
        self._string3 = self._validate(value)

    def __init__(self, string1=DEFAULT_STRING, string2=DEFAULT_STRING, string3=DEFAULT_STRING):
        self.string1 = string1
        self.string2 = string2
        self.string3 = string3

    def __str__(self):
        return ", ".join([self.string1, self.string2, self.string3)]

    def _validate(self, s):
        if s is not None and self.MIN_LEN <= len(s) <= self.MAX_LEN:
            return s
        else:
            return self.DEFAULT_STRING

通过定义自定义的类似属性的描述符,可以更加清晰地实现它。
class StringProperty:
    MIN_LEN = 1
    MAX_LEN = 50
    DEFAULT = "(undefined)"

    def __init__(self):
        self._d = {}

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return self._d[id(obj)]

    def __set__(self, obj, value):
        self._d[id(obj)] = self._validate(value)

    def _validate(self, s):
        if s is not None and self.MIN_LEN <= len(s) <= self.MAX_LEN:
            return s
        else:
            return self.DEFAULT_STRING

 class TripleString:
     string1 = StringProperty()
     string2 = StringProperty()
     string3 = StringProperty()

     def __init__(self, s1=None, s2=None, s3=None):
         self.string1 = s1
         self.string2 = s2
         self.string3 = s3

涉及验证此类属性的所有逻辑都封装在StringProperty类中。字典将其类具有StringProperty属性的对象的标识映射到该对象中的属性的值。所有作业均就地验证。
>>> x = TripleString("foo", "bar")
>>> x.string1, x.string2, x.string3
('foo', 'bar', '(undefined)')
>>> x.string2 = 'baz'
>>> x.string2
'baz'

访问值x.string1等效于TripleString.string1.__get__(x),而x.string2 = 'baz'等效于TripleString.string2.__set__(x, 'baz')

09-10 03:46