属性本质是方法,使用像字段
person.py
import datetime
class Person:
def __init__(self, name='', birthdate, gender='男', salary=0)
self.name = name
self.age = birthdate
self.gender = gender
self.salary = salary
//self._salary //_开头表示私有
@property //装饰器
def salary(self): //外部访问
return self._salary
@salary.setter
def salary(self, value):
if value <= 0:
self._salary = 0
else:
self._selary = value
def get_age(self):
return datetime.date.today().year - self.birthdate.year
@property
def age(self): //本质是方法,使用像字段
return datetime.date.today().year - aelf.birthdate.year
@age.setter
def age(self, value):
//raise ValueError('年龄不能赋值,只能通过生日计算!')
print('您赋的值是:', value)
print('年龄是通过生日计算的,不能手动赋值!')
def say(self, word):
print("{} say: {}".format(self.name, word))
def __str__(self):
return f'<Person {self.name}, {self.birthdate}, {self.gender}, {self.salary}>'
>>>import person
>>>p = Person('Tom', datetime.date(1990, 3, 3))
>>>print(p.age)
30
//属性默认下不能赋值,如果要赋值要写一个setter
// >>>p.age = 30 //AttributeErrpe: can't set attribute
//>>>p.age = 30
ValueError: 年龄不能赋值,只能通过生日计算
>>>p.age = 30
您赋的值是:30
年龄是通过生日计算的,不能手动赋值!