property将方法变为属性

首先,@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!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值