Home  >  Q&A  >  body text

python - creating managed attributes

Cookbook 8.6节有个例子:
http://chimera.labs.oreilly.com/books/1230000000393/ch08.html#_problem_124

class Person:
    def __init__(self, first_name):
        self.first_name = first_name

    # Getter function
    @property
    def first_name(self):
        return self._first_name

    # Setter function
    @first_name.setter
    def first_name(self, value):
        if not isinstance(value, str):
            raise TypeError('Expected a string')
        self._first_name = value

    # Deleter function (optional)
    @first_name.deleter
    def first_name(self):
        raise AttributeError("Can't delete attribute")

有个问题是,为什么__init__里面的是self.first_name而不是self._first_name,他说是

In this example, the entire point of the property is to apply type checking when setting an attribute. Thus, chances are you would also want such checking to take place during initialization. By setting self.first_name, the set operation uses the setter method (as opposed to bypassing it by accessing self._first_name).

我看不明白,求解释一下,多谢

天蓬老师天蓬老师2716 days ago722

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 14:22:41

    Initialize in

    __init__ to assign a value to first_name
    self.first_name is used here because
    @first_name.setter def first_name(self, value):

    If you use self._first_name directly, you will not enter
    @first_name.setter def first_name(self, value):

    There is no
    if not isinstance(value, str): raise TypeError('Expected a string')
    type checking.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:22:41

    Similar to java accessing private variables through getters, it avoids direct access to variables and is more standardized

    reply
    0
  • Cancelreply