python类中property的使用 - python 计算函数时间

1. 要解决的问题: 想要快速的访问类中的私有属性,但是不想直接暴露出原来类中的属性

@property    

def tick(self):

  return self._tick

 

2. 经典例子

复制代码
# property decorator make defining and modifying class's property easy
class Student:
@property
def score(self):
return self.__score

@score.setter
def score(self, score):
if isinstance(score, int):
self.__score = score
else:
raise TypeError('score must be int')


if __name__ == '__main__':
s = Student()
s.score = 'jjj'
print(s.score)
复制代码

 

3.  直接使用类的方法名字, 而不是直接使用类的属性

复制代码
class Student:
def __init__(self, score):
self.__score = score

def set_score(self, set_score):
self.__score = set_score

@property
def return_score(self):
return self.__score


if __name__ == '__main__':
s = Student(4)
print(s.return_score)
s.set_score(44)
print(s.return_score)
复制代码

参考: https://www.cnblogs.com/linuxchao/p/linuxchao-property.html

4.计算运行函数的时间差

start_time = time.perf_counter()
download_all(sites)
end_time = time.perf_counter()
print('Download {} sites in {} seconds'.format(len(sites), end_time - start_time))

 

posted @   littlevigra  阅读(101)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示