Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the function of the property attribute in Python

Shulou Source: shulou.com Published: 2022-06-01 00:02:02 10月04日 Update

This article mainly explains "what is the function of property attribute in Python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn "what is the role of the property attribute in Python"?

Preface

The concept of Python dynamic properties may be asked in an interview and is very useful in a project, but it is not mentioned in general programming tutorials, so you can learn more.

Let's start with a simple example. Create a Student class, I hope to get some information about each student through an example, including name, score, etc. The score will not be available until the end of the exam, so it will not be assigned a value when instantiated.

Class Student: def _ init__ (self, name): self.name = name self.score = Nonemike = Student ('mike')

After the exam, prepare to grade mike:

Mike.score = 999

Here, the teacher accidentally scored an extra 9, usually with a score of 100. 999 is an illegal data and should not be assigned successfully. As soon as there are more students, there will be more and more manual errors in teachers' scores, so we must find a way to modify the program to limit the value of score to 0-100.

Limit value

We define a method, if the input is not a 0-100 integer, let the program report an error, the data is legal, we will modify the score property successfully.

Def set_score (self, new_score): if not isinstance (new_score, int): raise ValueError ('score must be int') if 0 0: self._price = new_price else: raise' error: the price must be greater than zero'

Replace getter and setter with property

> class Watermelon (): def _ _ init__ (self,price): self._price = price @ property # use @ property decorate price method def price (self): return self._price @ price.setter # use @ property decorate method, when price is assigned Call decoration method def price (self,new_price): if new_price > 0: self._price = new_price else: raise 'error: price must be greater than zero' > watermelon = Watermelon (4) > watermelon.price4 > watermelon.price = 7 > watermelon.price7. I believe you have a better understanding of "what is the function of property attribute in Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Property method dynamic data method time private function achievement limitation utility success price content function student instance beginning situation program Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Information Shulou Tech Info MySQL MariaDB