36-@property装饰器

简介: Python

@property装饰器
Python内置的@property装饰器可以把类的方法伪装成属性调用的方式 。
class People:
def init(self, name, age):
self.__name = name
self.__age = age

@property
def age(self):

return self.__age

@age.setter
def age(self, age):

if isinstance(age, int):
    self.__age = age
else:
    raise ValueError

@age.deleter
def age(self):

print("删除年龄数据!")

obj = People(“jack”, 18)
print(obj.age)
obj.age = 19
print("obj.age: ", obj.age)
del obj.age

打印结果:
18
obj.age: 19
删除年龄数据!

将一个方法伪装成为属性后,就不再使用圆括号的调用方式了。而是类似变量的赋值、获取和删除方法了。当然,每个动作内部的代码细节还是需要你自己根据需求去实现的。

相关文章
|
8月前
|
JavaScript
Property “selectedItemIndex“ was accessed during render but is not defined on instance. 报错解决
Property “selectedItemIndex“ was accessed during render but is not defined on instance. 报错解决
715 0
|
8月前
|
iOS开发 MacOS
TypeError: Cannot read property ‘shop‘ of undefined
TypeError: Cannot read property ‘shop‘ of undefined
48 0
|
Java 数据库连接 mybatis
There is no getter for property named ‘null‘ in ‘class
There is no getter for property named ‘null‘ in ‘class
201 0
There is no getter for property named ‘null‘ in ‘class
|
Java 数据库连接 mybatis
mybatis报错:Type handler was null on parameter mapping or property ‘__frch_xxx_0’
mybatis报错:Type handler was null on parameter mapping or property ‘__frch_xxx_0’
2132 0
mybatis报错:Type handler was null on parameter mapping or property ‘__frch_xxx_0’
|
8月前
|
测试技术
ERROR [karma]_ TypeError_ Cannot read property 'unmask' of undefine
ERROR [karma]_ TypeError_ Cannot read property 'unmask' of undefine
62 0
|
8月前
|
JavaScript
Vue computed property values was assigned to but it has no setter
Vue computed property values was assigned to but it has no setter
130 0
|
JSON Java 数据格式
SpringMVC-@RequestMapping的参数和用法
SpringMVC-@RequestMapping的参数和用法
161 0
|
JavaScript CDN
Uncaught TypeError: Cannot redefine property: $router
Uncaught TypeError: Cannot redefine property: $router
226 0
MyBaits异常解决:There is no getter for property named ‘ID‘ in ‘class ***‘
MyBaits异常解决:There is no getter for property named ‘ID‘ in ‘class ***‘

热门文章

最新文章