【编程小知识杂记】Python中@property的用法

【编程小知识杂记】Python中@property的用法,第1张

1 前言

在使用算法做预测的时候,发现以前写的代码使用了property,但当时未了解透彻其用法,因此这里做一下简单的小结。

@attr.s
class LGBConfig(object):
    @property
    def num_leaves(self):
        return self._num_leaves

    @num_leaves.setter
    def num_leaves(self, value):
        if not isinstance(value, int):
            raise ValueError('max_depth must be an integer!')
        self._num_leaves = 2 ^ int(value)
2 使用场景

@property是一个装饰器,其主要的作用有以下两点:

2.1 改变方法的使用方式

可以将方法像类的属性一样使用:

class Person(object):
    def __init__(self):
        self.height = 180
        
    @property  
    def arm_length(self):
        return self.height
    
person = Person()
person.arm_length
# 不使用property的话获取arm_length的方法为person.arm_length(),就会涉及到传参的问题

2.2 防止属性值被恶意修改

比如在类定义了保护成员 self._age,但是外面可以修改这个_age。为了不让类外的 *** 作修改它,就可以使用property:

class Person(object):

	@property
	def age():
		return _age
# 这里不设置对应的setter,就起到了保护作用

# 而设置setter时候,也可以进行各种校验
	@age.setter
	def age(age_value):
		if not isinstance(age_value, int):
			raise ValueError('年龄必须是整数!')
		self._age = age_value
3 使用property的注意点

使用property需要注意以下两点:

  • 被property修饰的方法只有一个参数(self)
  • 它必须要有返回值

以下是本人独自运营的微信公众号,用于分享个人学习及工作生活趣事,大家可以关注一波。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/733689.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存