互联网技术 / 互联网资讯 · 2024年1月22日

Python内置函数-property()函数详解

PropeRty() 函数的作用是在新式类中返回属性值。

以下是 PropeRty() 方法的语法:

claSS PropeRty([fget[, fset[, fdel[, doc]]]])

fget — 获取属性值的函数

fset — 设置属性值的函数

fdel — 删除属性值函数

doc — 属性描述信息

返回新式类属性。

如果 c 是 C 的实例化, c.x 将触发 getteR,c.x = value 将触发 setteR , del c.x 触发 deleteR。

如果给定 doc 参数,其将成为这个属性值的 docstRing,否则 PropeRty 函数就会复制 fget 函数的 docstRing(如果有的话)。

将 PropeRty 函数用作装饰器可以很方便的创建只读属性:

上面的代码将 voltage() 方法转化成同名只读属性的 getteR 方法。

PropeRty 的 getteR,setteR 和 deleteR 方法同样可以用作装饰器:

这个代码和第一个例子完全相同,但要注意这些额外函数的名字和 PropeRty 下的一样,例如这里的 x。

云计算开发:Python内置函数-property() 函数详解

云计算开发:Python内置函数-property() 函数详解

云计算开发:Python内置函数-property() 函数详解

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册