首先,@property是在一个类里面装饰一个函数的,并且在实例化过后可以通过访问属性的形式来访问函数,举个例子
class Person:
@property
def work(self):
return "I am working"
def work2(self):
return "I am still working"
person = Person()
print(person.work)
print(person.work2())
打印结果为:
I am working
I am still working
可以看到没有用@property装饰的work2还是通过函数形式调用,而work看起来跟属性是一样的,但是如果尝试给work赋值就会报错:
class Person:
work3 = "test"
@property
def work(self):
return "I am working"
def work2(self):
return "I am still working"
person = Person()
person.work3 = 5
print(person.work3)
person.work = 6
print(person.work)
这里输出结果为:
5
Traceback (most recent call last):
File "D:/PycharmProjects/python_basic/property_method.py", line 15, in <module>
person.work = 6
AttributeError: can't set attribute
可以看到,property装饰的函数跟类里面的属性是有区别的,如果需要赋值,则需要添加@func.setter装饰,并且需要另外一个属性来传递参数:
class Person:
def __init__(self):
self._work = "I am working"
@property
def work(self):
return self._work
@work.setter
def work(self, value): # 函数名与@property下的相同
self._work = value # 这个是没有return的,所以需要self._work来传递值
person = Person()
print(person.work)
person.work = "I am still working"
print(person.work)
这里打印结果为:
I am working
I am still working
当然,@func.setter可以在赋值时对值进行加工:
class Person:
def __init__(self):
self._work = "I am working"
@property
def work(self):
return self._work
@work.setter
def work(self, value):
if value == "I am still working":
self._work = "You have to work till you die"
else:
self._work = "go to work!!!"
person = Person()
print(person.work)
person.work = "I am still working"
print(person.work)
person.work = "Let's eat chicken"
print(person.work)
这里打印结果为:
I am working
You have to work till you die
go to work!!!