python property对象

时间:2023-03-09 21:34:09
python property对象

一、从@porperty说起

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

class Stu(object):
def __init__(self,age):
self.__age=age
@property #直接调用属性
def birth(self):
return self._age
@birth.setter #设置属性
def birth(self, value):
self.__age = value
@birth.deleter #删除属性
def birth(self):
del self.__age #调用方法为
stu_a = Stu(3)
stu_a.birth # >>> 3 调用@property修饰的方法
stu_a.birth = 4 >>> 调用@setter修饰的方法
del stu_a.birth >>调用@deleter修饰的方法

二、property类

事实上property是一个类,里面封装了property,setter,deleter等方法,其中__init__()构造函数中,是存在4个参数的!

def __init__(self, fget=None, fset=None, fdel=None, doc=None):
pass

这也就是property的另一种用法:property()

class Stu(object):
def __init__(self,age):
self.__age=age
def get_age(self):
return self._age
def set_age(self, value):
self.__age = value
def del_age(self):
del self.__age
gsd = property(get_age, set_age, del_age) stu1 = Stu(1)
#调用方式:
stu1.gsd
stu1.gsd = 2
del stu1.gsd

三、自己的@property

@property其实就是通过描述符来定制,虽然内置方法为c封装的,但可以用python代码简单的实现@property的功能:

class B:  # property对象
def __init__(self, a): # 这里传入的是aa方法
self.a = func def __get__(self, instance, owner):
ret = self.func(instance) # instance为A的实例对象,即aa()函数需要的self
return ret class A:
@B # B = B(aa)
def aa(self):
return "property" b = A()
print(b.aa)