Python Objects
And Class
Defining a class in
python
class MyNewClass:
'''This is a docstring. I have created a new
class'''
pass
class MyClass:
"This is my second class"
a=10
def func(self):
print('Hello')
print(MyClass.a)
print(MyClass.func)
print(MyClass.__doc__)
Output
10
<function
0x7feaa932eae8="" at="" myclass.func="">
This is my second
class
Creating An Object In Python
# A simple example class
class Test:
# A
sample method
def
fun(self):
print("Hello
world")
# creating object to a class test
obj=Test()
#Executing the class method
obj.fun()
Output
Hello world
>>>obj=Test()
Examples
class BankAccount:
balance = 0
def
withdraw(self,amount):
self.balance-=amount
return
self.balance
def
deposit(self,amount):
self.balance
+= amount
return
self.balance
def
balanceCheck(self):
print("\n New
balance is...Rs.{}".format(self.balance))
def
bal_return(self):
return(self.balance)
BT=BankAccount()
while True:
print("1.
Deposit\n")
print("2.
Withdraw\n")
print("3.
Balance\n")
print("4.
Exit")
ch =
int(input("Enter your choice..."))
if ch == 1:
while
True:
amt=int(input("Enter
amount to Deposit..."))
if
amt>0:
BT.deposit(amt)
break
else:
print("Enter
Valid mount")
continue
if ch == 2:
while
True:
amt=int(input("Enter
amount to withdraw..."))
if
BT.bal_return()>amt:
BT.withdraw(amt)
break
else:
BT.balanceCheck()
print("\n Low
balance.please Enter Less Amount..")
continue
if ch ==3:
BT.balanceCheck()
if ch ==4:
break
Sample Input and output
1. Deposit
2. Withdraw
3. Balance
4. exit
Enter your Choice...1
Enter amount to deposit....2000
Enter your choice....1
Enter amount to deposit....-100
Enter Valid Amount
Enter amount to deposit...200
Enter Your choice...3
New balance is....Rs.2200
Enter your choice...2
Enter amount to withdraw...500
Enter your choice...3
New balance is...Rs.1700
Enter Your Choice....3
New balance is.....Rs.1700
Enter your Choice...2
Enter amount to withdraw....2000
low balance, please Enter less Amount..
Enter amount to withdraw...500
Enter your choice...3
New balance is...Rs.1200
0 comments:
Post a Comment