Python——property属性详解

property的主要作用

  • 在类中,当我们讲一个类方法用@property修饰时,意思就是将该函数当作类属性使用。
  • 需要注意的是,被@property修饰的类方法最好不要有除了self以外的参数,如果有,就体现不出@property的优势
  • 还有一个方便之处是,该修饰器可以替代get_xxx和set_xxx方法来获取或者设置类属性的值

例子

class Foo():
	def __init__(self):
		self.num = 100
		
	@property
	def prop(self):
		return self.num

foo = Foo(100)
print(foo.prop) # we use foo.prop() before,but here we remove the bracket

猜你喜欢

转载自blog.csdn.net/weixin_44441131/article/details/107371192