Python 之 Property

知识点:

1.property 作用 :相当于把类的方法封装,开发者在设置属性时更方便,还可以隐藏属性名字。

2.传统的调用 一个对象中的私有属性self.__x 可以采用setter 和 getter 方法 但是相对比较繁琐

3.property 第一种用法 num = property(getNum,setNum)  ,当程序执行 num = 1,程序会自动调用setNum方法 当程序执行 print(num) 时  程序会自动调用 getNum方法

4.property 第二种用法

@property 

def money(self):

       return self.num

@money.setter

def money(self,new_num)

        self.num = new_num

也可以通过money = 1 print(money) 访问私有元素

5. 在这里再补充一下私有问题

   __x 私有属性 只有本类的对象可用

   _x   禁止导入,但是类的对象和子类可用

  __x__  魔法方法 由python 自己定义 有特殊方法

   x__  用来解决关键字冲突问题。

# # class Test(object):
# #     def __init__(self):
# #         self.__num = 10
# #     def getNum(self):
# #         return self.__num
# #     def setNum(self,newnum):
# #         self.num = newnum
# # t = Test()
# # print(t.getNum())
# # t.setNum(50)
# # print(t.getNum())
# class Test(object):
#     def __init__(self):
#         self.__num = 10
#     def getNum(self):
#         return self.__num
#     def setNum(self,newnum):
#         self.__num = newnum
#     num = property(getNum,setNum)
# t = Test()
# t.num = 2
# print(t.num)
#property作用: 相当于把函数方法封装起来,开发者设置属性更加方便
class Test(object):
    def __init__(self):
        self.__num = 10
    @property
    def t_num(self):
        return self.__num
    @t_num.setter
    def t_num(self,newnum):
        self.__num = newnum
t = Test()
t.t_num = 1
print(t.t_num)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的property是一种特殊的装饰器,用于控制类属性的访问和修改。通过使用property,我们可以控制属性访问时的数据验证、数据转换等操作,以及保护属性的安全性。property通常由getter、setter和deleter三个方法组成,它们分别用于获取、设置和删除属性的值。其中,getter方法用于获取属性值,setter方法用于设置属性值,deleter方法用于删除属性值。 下面是一个简单的例子: ``` class Rectangle: def __init__(self, width, height): self._width = width self._height = height @property def width(self): return self._width @width.setter def width(self, value): if value <= 0: raise ValueError("Width must be positive.") self._width = value @property def height(self): return self._height @height.setter def height(self, value): if value <= 0: raise ValueError("Height must be positive.") self._height = value @property def area(self): return self._width * self._height ``` 在这个例子中,我们定义了一个Rectangle类,并为其定义了width、height和area三个属性。通过使用@property装饰器,我们为width和height属性定义了getter和setter方法,这样就可以控制属性访问时的数据验证。在这个例子中,如果尝试设置一个非正数的宽度或高度,就会抛出一个ValueError异常。 使用这个类的示例代码: ``` >>> r = Rectangle(3, 4) >>> r.width 3 >>> r.height 4 >>> r.area 12 >>> r.width = 5 >>> r.height = 6 >>> r.area 30 >>> r.width = -1 Traceback (most recent call last): ... ValueError: Width must be positive. ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值