IKH

Public, Protected and Private Attributes

  • By default every attribute is public. We can access from anywhere either within the class or from outside of the class.

Example

Python
name='Ajay'
Protected attributes can be accessed within the class anywhere but from outside of the class only 
in child classes. We can specify an attribute as protected by prefexing with _ symbol.

syntax

  • _variablename=value

Example

Python
_name='Ajay'
But is is just convention and in reality does not exists protected attributes.
private attributes can be accessed only within the class.i.e from outside of the class we cannot 
access. We can declare a variable as private explicitly by prefexing with 2 underscore symbols.

syntax

  • __variablename=value

Example

Python
 __name='Ajay'

Demo Program

Python
class Test: 
x=10 
_y=20 
__z=30 
def m1(self): 
print(Test.x) 
print(Test._y) 
print(Test.__z) 
 
t=Test() 
t.m1() 
print(Test.x) 
print(Test._y) 
print(Test.__z) 

Output

PowerShell
10
20
30
10
20
Traceback (most recent call last):
 File "test.py", line 14, in <module>
 print(Test.__z)
AttributeError: type object 'Test' has no attribute '__z'

How to access private variables from outside of the class

  • We cannot access private variables directly from outside of the class.
  • But we can access indirectly as follows objectreference._classname__variablename.

Example

Python
class Test: 
def __init__(self): 
self.__x=10 
 
t=Test() 
print(t._Test__x)#10 

str() method

  • Whenever we are printing any object reference internally __str__() method will be called which is returns string in the following format <__main__.classname object at 0x022144B0> To return meaningful string representation we have to override __str__() method.

Demo Program

Python
class Student: 
def __init__(self,name,rollno): 
self.name=name 
self.rollno=rollno 
 
def __str__(self): 
return 'This is Student with Name:{} and Rollno:{}'.format(self.name,self.rollno) 
 
s1=Student('Durga',101) 
s2=Student('Ravi',102) 
print(s1) 
print(s2)

Output without overriding str()

PowerShell
<__main__.Student object at 0x022144B0>
<__main__.Student object at 0x022144D0>

output with overriding str()

PowerShell
This is Student with Name:Ajay and Rollno:101
This is Student with Name:Prakhar and Rollno:102

Difference between str() and repr() OR Difference between str() and repr()

  • str() internally calls str() function and hence functionality of both is same
  • Similarly,repr() internally calls repr() function and hence functionality of both is same.
  • str() returns a string containing a nicely printable representation object.
  • The main purpose of str() is for readability.It may not possible to convert result string to original
  • object.

Example

Python
import datetime 
today=datetime.datetime.now() 
s=str(today)#converting datetime object to str 
print(s) 
d=eval(s)#converting str object to datetime

Output

PowerShell
6
  • D:\durgaclasses>py test.py 2018-05-18 22:48:19.890888 Traceback (most recent call last): File “test.py”, line 5, in d=eval(s)#converting str object to datetime File “”, line 1 2018-05-18 22:48:19.890888 ^ SyntaxError: invalid token
  • But repr() returns a string containing a printable representation of object.
  • The main goal of repr() is unambigouous. We can convert result string to original object by using eval() function,which may not possible in str() function.

Example

Python
import datetime 
today=datetime.datetime.now() 
s=repr(today)#converting datetime object to str 
print(s) 
d=eval(s)#converting str object to datetime 
print(d) 

Output

PowerShell
datetime.datetime(2018, 5, 18, 22, 51, 10, 875838)
2018-05-18 22:51:10.875838

Note

  • It is recommended to use repr() instead of str()

Mini ProjectBanking Application

Python
class Account: 
def __init__(self,name,balance,min_balance): 
self.name=name 
self.balance=balance 
self.min_balance=min_balance 
 
def deposit(self,amount): 
self.balance +=amount 
 
def withdraw(self,amount): 
if self.balance-amount >= self.min_balance: 
self.balance -=amount 
else: 
print("Sorry, Insufficient Funds") 
 
def printStatement(self): 
print("Account Balance:",self.balance) 
 
class Current(Account): 
def __init__(self,name,balance): 
super().__init__(name,balance,min_balance=-1000) 
def __str__(self): 
return "{}'s Current Account with Balance :{}".format(self.name,self.balance) 
 
class Savings(Account): 
def __init__(self,name,balance): 
super().__init__(name,balance,min_balance=0) 
def __str__(self): 
return "{}'s Savings Account with Balance :{}".format(self.name,self.balance) 
 
c=Savings("Durga",10000) 
print(c) 
c.deposit(5000) 
c.printStatement() 
c.withdraw(16000) 
c.withdraw(15000) 
print(c) 
 
c2=Current('Ravi',20000) 
c2.deposit(6000) 
print(c2) 
c2.withdraw(27000) 
print(c2)

Output

PowerShell
D:\durgaclasses>py test.py
Durga's Savings Account with Balance :10000
Account Balance: 15000
Sorry, Insufficient Funds
Durga's Savings Account with Balance :0
Ravi's Current Account with Balance :26000
Ravi's Current Account with Balance :-1000

Report an error