DEV Community

Connor Bode
Connor Bode

Posted on

@property decorator

Just a quick blurb about a nice feature in Python.

Let's say you have the following:

class Person:
  def __init__(self, first_name, last_name):
    self.first_name = first_name
    self.last_name = last_name

You can create a new person like:

mickey = Person('Micky', 'Mouse')
# spoiler, he's not actually a person

You might find yourself often wanting to get Mickey's full name, "Mickey Mouse" in your code. To do this, you'll probably do:

fullname = mickey.first_name + ' ' + mickey.last_name
# or maybe you'll use format, or printf, 
# depending on your style and how much coffee you've had that day.

Then, after you get tired of doing that all the time, you'll go back and add a method to your Person class:

class Person:
  def __init__(self, first_name, last_name):
    self.first_name = first_name
    self.last_name = last_name

  def name(self):
    return self.first_name + ' ' + self.last_name

and you'll instead use:

mickey.name()
# ==> Mickey Mouse

now.. the @property decorator really just gives us a coding style advantage. mickey.name would feel more natural than mickey.name(), since the name is always returning the same value, and feels more like a property than a function.

So how is it used?

Again, let's modify the class:

class Person:
  def __init__(self, first_name, last_name):
    self.first_name = first_name
    self.last_name = last_name

  @property
  def name(self):
    return self.first_name + ' ' + self.last_name

Then, we can get the name as follows:

mickey.name
# ==> Mickey Mouse

That's it for now! If you're interested in Python, Django, Linux, VIM, tmux (and all these other random tools in my tech stack) follow me on dev.to or on Twitter @connorbode.

I'll post tips as I code!

Top comments (0)