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 @ 2021-02-09 13:29  littlevigra  阅读(100)  评论(0编辑  收藏  举报