Last active
June 27, 2016 13:15
-
-
Save brainyfarm/a452071daaa6f254dd7691c3d93035ef to your computer and use it in GitHub Desktop.
Python Example Class and Data Encapsulation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This Gist demonstrate with a simple example | |
Classes and data encapsulation in python | |
""" | |
# Here, I create a class bankAccount | |
class bankAccount: | |
# Every new instance of bankAccount created must have a name, accountNumber and balance | |
# The __init__ method is a special method in python which is invoked when the new instance is created | |
# The self argument is a reference to that particular instance and it is important when invoking any method | |
def __init__(self, name, accountNumber, balance): | |
# Here we set the name property of this instance as the argument passed | |
# when the class was created (public property). | |
self.name = name | |
# number as accountNumber passed (public property) | |
self.number = accountNumber | |
# __balance as balance passed (__ signifies the property is private) | |
# This means it can only be accessed from members of the class | |
self.__balance = balance | |
# Here is a method within the bankAccount class and this method would have access to the private property __balance | |
# And that is because it is a member of the current class 'bankAccount' | |
def getBalance(self): | |
return self.__balance | |
# We create a new instance of bank account with its name, account number and balance | |
myAccount = bankAccount("Ade", 1101, 10000) | |
# Prints out "Ade" (public property) | |
print myAccount.name | |
# Prints out 1101 (public property) | |
print myAccount.number | |
# print myAccount.__balance Gives and error since __balance is private | |
#print myAccount.__balance | |
# Now let is try to get the balance which was private but now accessible | |
# from a method (getBalance) within its own class | |
print myAccount.getBalance() | |
# Now it returns 10000 :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment