美文网首页
8-1 Python的property

8-1 Python的property

作者: 正在努力ing | 来源:发表于2018-08-26 15:34 被阅读0次

假设以前有一个属性age,现在删掉了,通过函数get_age来做,此时就需要把全局的self.age 改为 get_age 很麻烦

现在就可以用@propert装饰器,把一个函数变成类的属性

from datetime import date,datetime

class User:
    def __init__(self,name,birth):
        self.name = name
        self.birth = birth
        # self.age = 0

    def get_age(self):
        return datetime.now().year - self.birth.year

    @property
    def age(self):
        return datetime.now().year - self.birth.year


user = User("zhou",date(year=1987,month=1,day=1))
print(user.age)

>>> 31

相关文章

  • 8-1 Python的property

    假设以前有一个属性age,现在删掉了,通过函数get_age来做,此时就需要把全局的self.age 改为 get...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • 2018-02-05

    python @property装饰器

  • Python中property中的小坑

    刚刚了解了python中的@property的使用,property本质是python中的一个内置修饰器。使用大概...

  • python @property

    参考 Python进阶之“属性(property)”详解 - Python - 伯乐在线

  • property, getter, setter and del

    http://www.runoob.com/python/python-func-property.htmlhtt...

  • Python的property

    取值和赋值 类Actress中有两个成员变量name和age。在外部对类的成员变量的操作,主要包括取值和赋值。简单...

  • Python property

    Question 我们一般对属性的的操作主要有2个,访问和修改。看个例子。 我们叫这种使用属性的方式叫点模式(我自...

  • python @property

    1.描述符 我们首先要搞懂描述符(Descriptor)是什么. 1.1 描述符定义 只要类中有__get__()...

  • Python @property

    以下内容来自万能的互联网... 首先教材上的@property 可以将一个方法的调用变成“属性调用”,主要用于帮助...

网友评论

      本文标题:8-1 Python的property

      本文链接:https://www.haomeiwen.com/subject/vweoiftx.html