Python property makes it easy to assign values to at­trib­ut­es from a Python class. You can call the cor­re­spond­ing getter and setter methods au­to­mat­i­cal­ly with Python property.

What is Python property and what is it used for?

Python property is a pro­gram­ming construct that de­vel­op­ers use in Pythonobject-oriented pro­gram­ming. Pro­gram­mers use prop­er­ties to define methods that can then be accessed like at­trib­ut­es. This provides intuitive access to the class’s at­trib­ut­es and makes calling dedicated setter and getter methods un­nec­es­sary. Python property turn class at­trib­ut­es into prop­er­ties, which are called “managed at­trib­ut­es”.

Python property also im­ple­ments its own access control. It uses prop­er­ties 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 in­ter­est­ed in Deploy Now. With this useful tool, you can build and deploy your code directly using GitHub.

What are the pa­ra­me­ters and the syntax for the Python property() function?

De­vel­op­ers can employ the Python-property() function when using prop­er­ties. This built-in function can be used without importing ad­di­tion­al modules. Python property() is im­ple­ment­ed in the C pro­gram­ming language, guar­an­tee­ing optimal per­for­mance.

The syntax for Python property() looks like this:

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

The pa­ra­me­ters for the function are optional. The following table provides an overview of the pa­ra­me­ters 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 dec­o­ra­tors are there?

You don’t have to use the property() function in order to work with prop­er­ties. You can also use pre­de­fined Python dec­o­ra­tors. This allows you to use a method from your class as a property. The pro­gram­ming language supports three different dec­o­ra­tors with the @ notation for defining prop­er­ties:

  • @property: Iden­ti­fies 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 in­ter­est­ed 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 il­lus­trate the func­tion­al­i­ty of Python property and how effective Python prop­er­ties are.

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

You may have noticed that the con­struc­tor doesn’t have a parameter spec­i­fy­ing 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 main­tain­abil­i­ty and ad­di­tion­al func­tion­al­i­ty. 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 cor­re­spond­ing function logic in a dedicated setter method and extend our class de­f­i­n­i­tion:

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 pro­gram­ming languages, Python does not offer a built-in way to dis­tin­guish between public and private class at­trib­ut­es. Public at­trib­ut­es are at­trib­ut­es outside of a class that can be accessed directly without getter and setter methods. Private at­trib­ut­es, on the other hand, cannot be easily modified from outside the class. To dis­tin­guish between the two types in Python, it is standard practice to begin variable name at­trib­ut­es that should only be accessed using getter and setter methods with an un­der­score.

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 un­der­score because Python property lets us address it from outside. The property() function now has the getter and setter methods as pa­ra­me­ters.

You can see the dif­fer­ence by creating another object in the class and naming it “Snoopy”:

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

The class’s at­trib­ut­es can now be easily accessed using dot notation. The program’s output is in­ter­est­ing:

Setter method called
Getter method called
'Snoopy'

The getter and setter methods were not ex­plic­it­ly 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 dec­o­ra­tors 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'
Go to Main Menu