Let’s look at another example. The following program shows a BankAccount class.
# defining BankAccount class
class BankAccount:
def __init__(self,amount):
self.__balance = amount
def deposit(self,amount):
self.__balance += amount
def withdraw(self,amount):
if self.__balance >= amount:
self.__balance -= amount
else:
print('Insufficient balance')
def get_balance(self):
return self.__balance
# Create BankAccount object and perform operations
amount = int(input('Enter the initial amount to open your account: '))
account = BankAccount(amount)
print('Your balance is', account.get_balance())
amount = int(input('Enter amount to deposit: '))
account.deposit(amount)
print('Your balance is', account.get_balance())
amount = int(input('Enter amount to withdraw: '))
account.withdraw(amount)
print('Your balance is', account.get_balance())
Output
Enter the initial amount to open your account: 500 Your balance is 500 Enter amount to deposit: 1200 Your balance is 1700 Enter amount to withdraw: 800 Your balance is 900
The following Point class demonstrates how objects are passed as arguments.
# creating Point class
import math
class Point:
def __init__(self, x=0, y=0):
self.__x = x
self.__y = y
def distance(self, other):
xd = self.__x - other.__x;
yd = self.__y - other.__y;
return math.sqrt(xd**2 + yd**2)
def equals(self, other):
if self.__x == other.__x and self.__y == other.__y:
return True
else:
return False
def __str__(self):
return '('+ str(self.__x) +', ' + str(self.__y) + ')'
# Creating Point objects
p1 = Point(4,6)
p2 = Point(6,8)
print('Point 1:', p1)
print('Point 2:', p2)
if p1.equals(p2):
print('Points are equals')
else:
print('Point are not equals')
d = p1.distance(p2)
print('Distance between points are',d)
Output
Point 1: (4, 6) Point 2: (6, 8) Point are not equals Distance between points are 2.8284271247461903