zoukankan      html  css  js  c++  java
  • python类中property的使用

    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))
    用一个例子来演示会更加清晰
  • 相关阅读:
    派生选择器
    HTML 标签
    $.get()
    CC150
    CC150
    CC150
    CC150
    HashMap和HashTable的区别
    CC150
    quickSort
  • 原文地址:https://www.cnblogs.com/hixiaowei/p/14392671.html
Copyright © 2011-2022 走看看