Python中如何使用property属性定义属性访问器?

2026-06-11 10:272阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计357个文字,预计阅读时间需要2分钟。

Python中如何使用property属性定义属性访问器?

创建property属性的方法有两种,分别是装饰器方式和属性方式。1、装饰器方式如下:

pythonclass Goods: def __init__(self): self.original_price=100 self.discount=0.8

@property def price(self):

2、属性方式如下:

pythonclass Goods: def __init__(self): self._original_price=100 self._discount=0.8

@property def price(self): return self._original_price * self._discount

创建property属性的方法有两种,分别是 装饰器方式 和 类属性方式。

Python中如何使用property属性定义属性访问器?

1、装饰器方式如下:

class Goods: def __init__(self): self.original_price = 100 self.discount = 0.8 @property def price(self): #此函数中只有self,不能有其他参数穿进 new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deleter def price(self): del self.original_price g = Goods() price = g.price g.price = 60 del g.price print(g.original_price)

2、 类属性方式如下:

1 class Goods(): 2 def get_price(self): 3 return 100 4 5 def set_price(self, value): 6 """必须两个参数""" 7 return value 8 9 def del_price(self): 10 return ‘no price‘ 11 12 BAR = property(get_price, set_price, del_price) 13 14 obj = Goods() 15 16 obj.BAR # 自动调用第一个参数中定义的方法:get_price 17 obj.BAR = 50 # 自动调用第二个参数中定义的方法:set_price方法,并将50当作参数传入 18 del obj.BAR # 自动调用第三个参数中定义的方法:del_bar方法

此外,property还有 doc 属性,此参数是该属性的描述信息,不过一般用不上,所以不介绍。

本文共计357个文字,预计阅读时间需要2分钟。

Python中如何使用property属性定义属性访问器?

创建property属性的方法有两种,分别是装饰器方式和属性方式。1、装饰器方式如下:

pythonclass Goods: def __init__(self): self.original_price=100 self.discount=0.8

@property def price(self):

2、属性方式如下:

pythonclass Goods: def __init__(self): self._original_price=100 self._discount=0.8

@property def price(self): return self._original_price * self._discount

创建property属性的方法有两种,分别是 装饰器方式 和 类属性方式。

Python中如何使用property属性定义属性访问器?

1、装饰器方式如下:

class Goods: def __init__(self): self.original_price = 100 self.discount = 0.8 @property def price(self): #此函数中只有self,不能有其他参数穿进 new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deleter def price(self): del self.original_price g = Goods() price = g.price g.price = 60 del g.price print(g.original_price)

2、 类属性方式如下:

1 class Goods(): 2 def get_price(self): 3 return 100 4 5 def set_price(self, value): 6 """必须两个参数""" 7 return value 8 9 def del_price(self): 10 return ‘no price‘ 11 12 BAR = property(get_price, set_price, del_price) 13 14 obj = Goods() 15 16 obj.BAR # 自动调用第一个参数中定义的方法:get_price 17 obj.BAR = 50 # 自动调用第二个参数中定义的方法:set_price方法,并将50当作参数传入 18 del obj.BAR # 自动调用第三个参数中定义的方法:del_bar方法

此外,property还有 doc 属性,此参数是该属性的描述信息,不过一般用不上,所以不介绍。