天天看點

python中property方法有用_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