A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/getter-and-setter-in-python/ below:

Getter and Setter in Python

Getter and Setter in Python

Last Updated : 11 Jul, 2025

In Python, a getter and setter are methods used to access and update the attributes of a class. These methods provide a way to define controlled access to the attributes of an object, thereby ensuring the integrity of the data. By default, attributes in Python can be accessed directly. However, this can pose problems when attributes need validation or transformation before being assigned or retrieved.

Python provides several ways to implement getter and setter methods:

Using normal function

In this approach, getter and setter methods are explicitly defined to get and set the value of a private variable. The setter allows setting the value and the getter is used to retrieve it.

Python
class Geek: 
	def __init__(self, age = 0): 
		self._age = age 
	
	# getter method 
	def get_age(self): 
		return self._age 
	
	# setter method 
	def set_age(self, x): 
		self._age = x 

raj = Geek() 

# setting the age using setter 
raj.set_age(21) 

# retrieving age using getter 
print(raj.get_age()) 

print(raj._age) 

Explanation:

Using property() function

In this method, the property() function is used to wrap the getter, setter and deleter methods for an attribute, providing a more streamlined approach.

Python
class Geeks: 
	def __init__(self): 
		self._age = 0
	
	# function to get value of _age 
	def get_age(self): 
		print("getter method called") 
		return self._age 
	
	# function to set value of _age 
	def set_age(self, a): 
		print("setter method called") 
		self._age = a 

	# function to delete _age attribute 
	def del_age(self): 
		del self._age 
	
	age = property(get_age, set_age, del_age) 

mark = Geeks() 

mark.age = 10

print(mark.age) 

Output
setter method called
getter method called
10

Explanation:

Using @property decorators

In this approach, the @property decorator is used for the getter and the @<property_name>.setter decorator is used for the setter. This approach allows a more elegant way to define getter and setter methods.

Python
class Geeks: 
	def __init__(self): 
		self._age = 0
	
	# using property decorator 
	# a getter function 
	@property
	def age(self): 
		print("getter method called") 
		return self._age 
	
	# a setter function 
	@age.setter 
	def age(self, a): 
		if(a < 18): 
			raise ValueError("Sorry you age is below eligibility criteria") 
		print("setter method called") 
		self._age = a 

mark = Geeks() 

mark.age = 19

print(mark.age) 

Output
setter method called
getter method called
19

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4