美文网首页
Python property的使用

Python property的使用

作者: i_promise | 来源:发表于2018-03-08 10:38 被阅读6次

1、

 class Test(object):

     def __init__(self):
         self.__num = 100
     def getNum(self):
         print('------getter-----')
         return self.__num
     def setNum(self, newNum):
         print('-------setter---------')
         self.__num = newNum
     num = property(getNum, setNum)

t = Test()
print(t.num)
t.num = 200   #相当于调用了t.setNum()
print(t.num)  #相当于调用了t.setNum(200)

输出:
------getter-----
100
-------setter---------
------getter-----
200
property的作用:相当于把方法进行了封装,开发者在对属性设置数据的时候更方便

2、

class Money(object):
    def __init__(self):
        self.__money = 0

    @property
    def money(self):
        return self.__money

    @money.setter
    def money(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print('errpr 不是整型数字')

a = Money()
print(a.money)
a.money = 500
print(a.money)

相关文章

  • Python中property中的小坑

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

  • Python使用@property

    在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: 这显然不...

  • python 使用 @property

    引用-廖雪峰 背景 在设置属性时,可以直接把属性暴露出去,这个简单,但是会导致被随意修改属性值。 为了避免上面值被...

  • python 使用@property

    比get、set方法实现起来更简单

  • python @property的使用

    为了保持数据的封装性,使用setXXX(), getXXX()方法获取数据 为了让访问这两个方法像直接访问属性那样...

  • Python property的使用

    1、 输出:------getter-----100-------setter---------------get...

  • Python学习笔记(十七)使用@property,多重继承

    使用@property Python内置的@property装饰器就是负责把一个方法变成属性调用的 把一个gett...

  • python中@property的使用

    今天遇到一个问题: 报错了,经过改正后的代码如下: 想不到吧,一个小小的下划线竟然是罪魁祸首。不过还是不能理解,为...

  • Python进阶——面向对象

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

  • Python @property 详解

    一、概述 python中 @property 是python的一种装饰器,是用来修饰方法的。我们可以使用@pro...

网友评论

      本文标题:Python property的使用

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