1. 程式人生 > >python Class:面向對象高級編程 @property

python Class:面向對象高級編程 @property

odi ack sel color birt -a oat nor family

看不懂,先記錄


一、

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


class Student(object):

@property
def score(self):
return self._score

@score.setter #setter是哪裏來的??作用呢???
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')

if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value


s = Student()
s.score = 60
print s.score


運行結果:60


二、

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Student1(object):

@property #????
def birth(self):
return self._birth

@birth.setter #????
def birth(self, value):
self._birth = value

@property #????
def age(self):
return 2014 - self._birth


s = Student1()
s.birth = 60
print s.age


運行結果:60


python Class:面向對象高級編程 @property