Malekai
Malekai

Reputation: 5031

What is a "property" used for in Python?

I was editing a blog post and started to type the word property when my autocomplete suggested a completion called new Property, curious as ever I looked it up and found that this was coming from the Python autocomplete package.

I pressed it and this code appeared:

def foo():
  doc = "The  property."

  def fget(self):
    return self._

  def fset(self, value):
    self._ = value

  def fdel(self):
    del self._

  return locals()

 = property(**())

I typed Grape where the cursor(s) were, so I ended up with this:

def Grape():
  doc = "The Grape property."

  def fget(self):
    return self._Grape

  def fset(self, value):
    self._Grape = value

  def fdel(self):
    del self._Grape

  return locals()

Grape = property(**Grape())

By looking at the code I can see that it's creating a local variable called doc but doesn't seem to be doing anything with it.

It's also creating three functions, one which returns self._Grape another which adds a new property to self._Grape and one which deletes self._Grape.

Where did self & _Grape come from? Is this a class of some sort, like a "pseudo class"?

Where, why and how are "new Properties" used?

Upvotes: 0

Views: 74

Answers (1)

Javier
Javier

Reputation: 2776

Your editor is providing an unusual way to create a property. Here is some information on properties.

After reading that, you'll realize that there's no need to create the getter and setter within a function. The reason the editor does it this way is to have a scope where to define the names of the getter and setter without needing unique names. IOW, the names are hidden in the function.

So, how are the objects defined in the function (fget, fset, fdel & doc) passed to the property descriptor?

Notice the function returns the result of locals. So the return value of the function is a dict with the name of the local objects as keys and the local objects as values.

Finally, regarding self, fget, fset and fdel will be executed as if they were methods of the object which has the property so self refers to that object.

Upvotes: 1

Related Questions