@property和@属性.setter的用法

class Person(object):
    """人"""

    def __init__(self, name, age):
        self._name = name
        self._age = age

    @property
    def name(self):
        return self._name

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, age):
        self._age = age

    def play(self):
        print('%s正在愉快的玩耍.' % self._name)

    def watch_av(self):
        if self._age >= 18:
            print('%s正在观看爱情动作片.' % self._name)
        else:
            print('%s只能观看《熊出没》.' % self._name)

if __name__ == '__main__':
person = Person(name="jason",age=18)
print(person.age)
person.age = 30
print(person.age)


-----------------------------------------------------------------------------------------------

C:\xxx\python.exe C:/Users/PycharmProjects/xxx/xxx/xxx.py
18
30

  @property是类属性方法, @属性.setter 就是给@property装饰的类属性添加可赋值操作

上一篇:Vue面试题之响应式原理


下一篇:特殊类 --》JavaBeans