Skip to content

Python getters and setters

AndrewMZ edited this page Jun 11, 2022 · 1 revision

Setters are called when there's assignment to an attribute happens - @property decorator Getters are called when an attribute gets accessed - attr_name.setter decorator

class MyClass:
	def __init__(self, first, last):
		self.first = first
		self.last = last

	@property
	def fullname(self):
		return f"{self.first} {self.last}"

	@fullname.setter
	def fullname(self, name):
		self.first, self.last = name.split(' ')

# creating instance of MyClass
e = MyClass("John", "Smith")
print(f"fullname = {e.fullname}")

# changing last name and fullname autoatically changes too
# since getter for fullname works here
e.last = "Doe"
print(f"fullname = {e.fullname}")

# setting fullname and it changes first and last attributes
# since setter for fullname works here
e.fullname = "Lisa Shpitswerg"
print(f"first = {e.first}, last = {e.last}")

output:

fullname = John Smith
fullname = John Doe
first = Lisa, last = Shpitswerg

When attribute e.fullname gets accessed it gets evaluated in @property -> fullname method, whilst when e.fullname assigned some value it is @fullname.setter that comes into play