Python Getters & Setters: 2 Ways To Implement (2 Min)

preview_player
Показать описание
In this tutorial, you'll learn how to implement getters and setters in Python.


Video Transcript:


Hi guys, this is Abhi from Gokcedb. In this video, you're going to learn two ways to implement getters and setters in Python. Number one using the property function.

Here I'm defining a class called MySQL with three methods. Unerscore underscore init underscore underscore is a special method used to initialize instance variables. The get underscore number of tables method is acting as a getter here because it's returning the value of a number of tables variable.

Whereas the set underscores a number of tables method is acting as a setter because it's setting a new value for the number of the table variable. I'm also raising a value error exception in case the number provided is negative. On line 19, I'm using the property function to create the number of tables as a property of the MySQL class.

The first argument to the property function is a getter and the second argument is a setter. On line 23, I'm using the DB1 object to set a value of 5 to number of tables property. Watch what happens when I try to set a negative value.

I get a value error exception as expected. Number two another way to implement getters and setters is by using the at-property decorator. On line 33, I'm specifying the number of tables as a property of the MySQL2 class.

If we try to set a negative value we should get an exception just like before. There you have it. Make sure you like, subscribe, and turn on the notification bell.

Until next time.
--
# 1. Using the property function
class MySQL:
def __init__(self):
self._number_of_tables = 0

def get_number_of_tables(self):
print("inside getter method")
return self._number_of_tables

def set_number_of_tables(self, num):
print("inside setter method")
if num [removed] 0:
raise ValueError("Invalid value provided for number of tables")
else:
self._number_of_tables = num

number_of_tables = property(get_number_of_tables, set_number_of_tables)

db1 = MySQL()

# 2. Using the @property decorator
class MySQL2:
def __init__(self):
self._number_of_tables = 0

@property

def number_of_tables(self):
print("inside getter method")
return self._number_of_tables

def number_of_tables(self, num):
print("inside setter method")
if num [removed] 0:
raise ValueError("Invalid value provided for number of tables")
self._number_of_tables = num

db2 = MySQL2()
Рекомендации по теме
welcome to shbcf.ru