python 属性property

2019-12-13 13:12:37 浏览数 (1)

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

代码语言:javascript复制
# 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")

0 人点赞