diff --git a/OOP/P12_GetterSetterMethods.py b/OOP/P12_GetterSetterMethods.py new file mode 100644 index 0000000..96eb887 --- /dev/null +++ b/OOP/P12_GetterSetterMethods.py @@ -0,0 +1,37 @@ +''' +Author: AMIT PATHAK + +In this example, we will the getter and setter methods in python class. +Private variables of a class cannot be accessed outside the class using the class object. +In order to access or manipulate these variables, we make use of getter and setter methods respectively. +''' + +class CreditCard(object): + + def __init__(self, number, new_pin): + self.card_number = number + self.__pin = new_pin # Private Variable + + def get_pin(self): + return self.__pin + + def set_pin(self, new_pin): + self.__pin = new_pin + + +if __name__ == '__main__': + + cc = CreditCard(number=514235895214, new_pin=1234) + + print(cc.card_number) + ### Output: 514235895214 + + #print(cc.__pin) + ### Output: AttributeError: 'CreditCard' object has no attribute '__pin' + + print(cc.get_pin()) + ### Output: 1234 + + cc.set_pin(new_pin=8745) # Set a new pin to 8745 + print(cc.get_pin()) + ### Output: 8745 diff --git a/README.md b/README.md index c79a6c5..d8418ea 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ Pune, Maharashtra, India.
6. [Multiple Inheritance](https://github.com/OmkarPathak/Python-Programs/blob/master/OOP/P08_MultipleInheritence.py) 7. [Private Variables](https://github.com/OmkarPathak/Python-Programs/blob/master/OOP/P10_PrivateVariable.py) 8. [Magic Methods](https://github.com/OmkarPathak/Python-Programs/blob/master/OOP/P11_MagicMethods.py) +9. [Getter & Setter Methods](https://github.com/OmkarPathak/Python-Programs/blob/master/OOP/P12_GetterSetterMethods.py) ## Trees