Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getter-setter methods example #74

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions OOP/P12_GetterSetterMethods.py
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ Pune, Maharashtra, India.<br />
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

Expand Down