Python面向对象之属性

属性的定义和调用

1,定义时,在普通方法的基础上添加@property装饰器

2,定义时,属性仅有一个self参数

3,调用时,无需括号

vim day7-8.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python
# -*- coding:utf-8 -*-
class Pager():
 
    def __init__(self,current_page):
        self.current_page = current_page                        #代表第几页
        self.per_items = 10                                     #每页显示行数
 
    @property
    def start(self):                                            #开始的序号
        val = (self.current_page - 1) * self.per_items + 1
        return val
 
 
    @property
    def end(self):                                              #结束序号
        val = self.current_page * self.per_items
        return val
 
p = Pager(2)
print p.start
print p.end

使用以上方法可以根据页数取得需要查询的数据的序号开始和结束值

这里使用属性的方法是为了调用看起来更加合理

取消属性装饰器,调用的时候就要加()

所以以上代码和以下代码的效果的一样的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python
# -*- coding:utf-8 -*-
class Pager():
 
    def __init__(self,current_page):
        self.current_page = current_page                        #代表第几页
        self.per_items = 10                                     #每页显示行数
 
 #   @property
    def start(self):                                            #开始的序号
        val = (self.current_page - 1) * self.per_items + 1
        return val
 
 
 #   @property
    def end(self):                                              #结束序号
        val = self.current_page * self.per_items
        return val
 
p = Pager(2)
print p.start()
print p.end()

PS:属性在编程时可能用不上,知道即可

  属性有两种表达方式一种是加property装饰器一种是使用property方法

 

对于新式类不仅仅支持property还支持

vim day7-9.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/python
# -*- coding:utf-8 -*-
class Goods(object):
 
    @property
    def price(self):
        print '@property'
 
    @price.setter
    def price(self,value):
        print '@property.setter'
 
    @price.deleter
    def price(self):
        print '@property.deleter'
 
 
obj = Goods()
 
obj.price       #自动执行 @property修饰的price方法,并获取方法的返回值
obj.price = 123 #自动执行 @price.setter装饰的price方法,并将123赋值给方法
del obj.price   #自动执行 @price.deleter装饰的price方法
~                                                       

PS:知道即可,很少用

 

posted @   minseo  阅读(234)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示