How to use Python property

Python property makes it easy to assign values to attributes from a Python class. You can call the corresponding getter and setter methods automatically with Python property.

What is Python property and what is it used for?

Python property is a programming construct that developers use in Pythonobject-oriented programming. Programmers use properties to define methods that can then be accessed like attributes. This provides intuitive access to the class’s attributes and makes calling dedicated setter and getter methods unnecessary. Python property turn class attributes into properties, which are called “managed attributes”.

Python property also implements its own access control. It uses properties to ensure that other methods are unable to access the attribute’s data and make changes to it.

Tip

If you use Python to create web-based projects, you may also be interested in Deploy Now. With this useful tool, you can build and deploy your code directly using GitHub.

What are the parameters and the syntax for the Python property() function?

Developers can employ the Python-property() function when using properties. This built-in function can be used without importing additional modules. Python property() is implemented in the C programming language, guaranteeing optimal performance.

The syntax for Python property() looks like this:

property(fget=None, fset=None, fdel=None, doc=None)
Python

The parameters for the function are optional. The following table provides an overview of the parameters and explains what each parameter means:

Parameter Meaning
fget Function that returns an attribute’s value (getter method)
fset Function that allows you to set an attribute’s value (setter method)
fdel Function that specifies how to delete attribute
doc Python string that describes the property

What Python property decorators are there?

You don’t have to use the property() function in order to work with properties. You can also use predefined Python decorators. This allows you to use a method from your class as a property. The programming language supports three different decorators with the @ notation for defining properties:

  • @property: Identifies your class’s method as a Python property
  • @property-name.setter: Specifies a setter method that sets the property’s value
  • @property-name.deleter: Specifies the method that deletes a property
Note

If you are interested in advanced Python tutorials, check out the following articles in our Digital Guide:

Python property code examples

The following code snippet creates a class called “dog” with the attribute “_name”. While this example has no value in the real world, it helps to illustrate the functionality of Python property and how effective Python properties are.

class dog:
	def __init__(self):
		self._name = "Bello"
Python

You may have noticed that the constructor doesn’t have a parameter specifying the dog’s name. Instead, the default value for the dog’s name has been set to “Bello”. In this case, you can create an object of the class with the following line of code:

dog = dog()

Getter and setter methods

You can extend your class with specific getter and setter methods. This is useful for code maintainability and additional functionality. Since names are strings by default, we want to ensure that the name is passed into our class as a string. To do this, we need to write the corresponding function logic in a dedicated setter method and extend our class definition:

class dog:
	def __init__(self):
		self._name = "Bello"
	
	def getName(self):
		return self._name
	def setName(self, name):
		if isinstance(name, str):
			self._name = name
		else:
			return
Python

A Python if-else statement in “setName” is used to check whether the parameter passed is a string. If it is, the name is set, otherwise nothing will happen.

We also specify a getter method that returns the dog’s name.

An object named “Lassie” can be created like this:

lassie = dog()
lassie.setName("Lassie")
print(lassie.getName())
Python

The output looks like this:

'Lassie'
Note

Unlike other programming languages, Python does not offer a built-in way to distinguish between public and private class attributes. Public attributes are attributes outside of a class that can be accessed directly without getter and setter methods. Private attributes, on the other hand, cannot be easily modified from outside the class. To distinguish between the two types in Python, it is standard practice to begin variable name attributes that should only be accessed using getter and setter methods with an underscore.

Python property() function

We can use Python property to change or learn the name of our Python dog without having to use an explicit function call. In the following example, we are going to include a print statement in each of our getter and setter methods.

class dog:
	def __init__(self):
		self._name = "Bello"
	def getName(self):
		print("Getter method called")
		return self._name
	def setName(self, name):
		if isinstance(name, str):
			self._name = name
			print("Setter method called")
		else:
			return
	
	name = property(getName, setName)
Python

As you can see, we created a new attribute called “name” in order to call the property() function and assigned the result of the function’s call to it. We did this without an underscore because Python property lets us address it from outside. The property() function now has the getter and setter methods as parameters.

You can see the difference by creating another object in the class and naming it “Snoopy”:

snoopy = dog()
snoopy.name = "Snoopy"
snoopy.name
Python

The class’s attributes can now be easily accessed using dot notation. The program’s output is interesting:

Setter method called
Getter method called
'Snoopy'

The getter and setter methods were not explicitly called, but they were executed the moment the name of the Snoopy object was assigned using dot notation. This is thanks to Python property.

Python property decorator

You can achieve the same effect using the function decorators mentioned above. Keep in mind that the two methods being decorated should have the same name. The sample code looks like this:

class dog:
	def __init__(self):
		self._name = "Bello"
	@property
	def name(self):
		print("Setter method called")
		return self._name
	@name.setter
	def name(self, name):
		if isinstance(name, str):
			self._name = name
			print("Getter method called")
		else:
			return
Python

You can create an object of your class and use dot notation to set and read the “name” attribute:

snowy = dog()
snowy.name = "Snowy"
snowy.name
Python

The output is the same as when using Python property():

Setter method called
Getter method called
'Snowy'
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.