Python – Getter and Setter Methods

Getter Method – This method is used to access or read data of the variables. This method does not modify the data in the variable. This is also called as Accessor Method.

In other words, the methods for retrieving or accessing the values of attributes are called Getter Methods.

Example –

def getValue(self):
def getName(self):
def getResult(self):
def getId(self):

Please have a look at example.

class Mobile:
    def __init__(self):
        self.model = 'iPhone 12'
    def getModel(self):
        return self.model

iphone = Mobile()
m = iphone.getModel()
print(m)

#OUTPUT
iPhone 12

Setter method – This method is used for changing the values of attributes are called Setter Methods. This is also called Mutator method.

Example –

def setValue(self):
def setName(self):
def setResult(self):
def setId(self):

Let us take an example.

class Mobile:
    def __init__(self):
        self.model = 'iPhone 12'

    def setModel(self):
        self.model = 'iPhone 12 Pro'

    def getModel(self):
        return self.model

iphone = Mobile()
iphone.setModel()
m = iphone.getModel()
print(m)

#OUTPUT
iPhone 12 Pro

We can also achieve the above program as given below.

class Mobile:
    def setModel(self, model):
        self.model = model

    def getModel(self):
        return self.model

iphone = Mobile()
iphone.setModel('iPhone Pro Max')
m = iphone.getModel()
print(m)

#OUTPUT
iPhone 12 Pro

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial