Role of self-object
1) Memory allocation for object
2) Memory reference returned to the object
3) Memory reference automatically passed inside constructor.
4) Constructor creates/initialize variables at the memory reference.
class Employee:
def __init__(self, nm, ag):
[Link]=nm
[Link]=ag
e1=Employee(Jai, 24)
e2=Employee(Raj, 28)
print(getattr(e1, __dict__))
Built-in class function
• getattr(object_name, attribute_name)
• setattr(object_name, attribute_name, new_value)
• delattr(object_name, attribute_name)
• hasattr(object_name, attribute_name)
class Employee:
def __init__(self, nm, ag):
[Link]=nm
[Link]=ag
e1=Employee(Jai, 24)
e2=Employee(Raj, 28)
print(getattr(e1, age))
setattr(e2, ‘name’, ‘Jairaj’)
print(getattr(e2, __dict__))
delattr(e2, ‘age’)
print(getattr(e2, __dict__))
print(hasattr(e1, ‘name’))
Built-in class attribute
• __dict__: Dictionary containing class’s namespace
• __doc__: Class documentation string.
• __name__: Class name
• __modlule__: Module name in which class is defined.
• __bases__: List of base classes.
class Employee:
def __init__(self, sal, ag):
[Link]=sal
[Link]=ag
def display:
print(f”name is {[Link]} and age is {[Link]}”)
e1=Employee(24000, 24)
e2=Employee(30000, 28)
#Accessing attribute outside the class
print([Link])
[Link]=40000 # updating attribute
print([Link])
class Employee:
def __init__(self, nm, ag):
[Link]=nm
[Link]=ag
e1=Employee(Jai, 24)
e2=Employee(Raj, 28)
print(Employee.__doc__)
print(Employee.__dict__)
print(Employee.__name__)
print(Employee.__module__)
class Demo:
Pass
D1=Demo()
class Employee:
def __init__(self, nm, ag):
[Link]=nm
[Link]=ag
def display:
print(f”name is {[Link]} and age is {[Link]}”)
e1=Employee(Jai, 24)
e2=Employee(Raj, 28)
isinstance(e1, Employee)
Instance Variable
Variable made for particular instance.
Separate copy created for every object.
Values of variables differs from object to object.
Modification in one object won’t affect objects.
Creating Instance Variable
• Using constructor
• Using Instance method
• Outside class
Class variable and class method
Class variable
• Variable made for entire class (All object)
• Only one copy created and shared to all objects.
• Modification in class variable impact on all objects.
class Employee:
company_name=”infosys” #class variable
def __init__(self, sal, ag):
[Link]=sal
[Link]=ag
e1=Employee(24000, 24)
e2=Employee(30000, 28)
e2.company_name=”TCS”
print(e2.__dict__)
print(e1.__dict__)
print(Employee.company_name)
Modification in the class variable can be done by using class name only. Not by the reference or object.
Class Method
• Method which works on class variables.
• First argument is class reference.
• Made using decorator ‘@classmethod’
class Employee:
company_name=”infosys” #class variable
def __init__(self, nm, sal):
[Link]=nm
[Link]=sal
@classmethod
def get_company_name(cls):
print(f”company name is:”, cls.company_name)
OR
cls.company_name=”TCS”
print(cls.company_name)
e1=Employee(Jai, 3000)
e2=Employee(Raj, 6000)
Employee. company_name()
print(e2.company_name)
Instance Method
Setter: Set value of instance variable.
Getter: Get value of instance variable.
class Employee:
def setName(self, nm):
[Link]=nm
def getName(self, nm):
print(“The name is:”, [Link])
e1=Employee()
e2=Employee()
[Link](input(“Enter the name:”))
[Link](input(“Enter the name:”))
print(“e1 object is:”, e1.__dict__)
print(“e2 object is:”, e2.__dict__)
[Link]()
[Link]()
Static Method
• Operation which performs operation on external data.
• It can also perform operation on class data.
• No need to pass object or class reference.
• Created using decorator ‘@staticmethod’
Class Bank:
Bank_name=’BOI’
Rate_of_interest=12.5
@staticmethod
Def simple_interest(prin, n):
Si=(prin*n*rate_of_interest)/100
Prin=float(input(“Enter principle amount:”))
n=int(input(“Enter number of years:”))
Bank.simple_of_interest(prin, n)
Advantages of Static Method
• It can be used as a utility function to perform frequently re-used tasks.
• We can invoke this method using the class name. Hence, it eliminates the dependency on
the instances.
• A static method is always predictable.
• We can declare a method as a static method to prevent overriding.
Python - Access Modifiers
The Python access modifiers are used to restrict access to class members (i.e., variables and
methods) from outside the class. There are three types of access modifiers namely public, protected,
and private.
• Public members − A class member is said to be public if it can be accessed from
anywhere in the program.
• Protected members − They are accessible from within the class as well as by classes
derived from that class.
• Private members − They can be accessed from within the class only.
Usually, methods are defined as public and instance variable are private. This arrangement of
private instance variables and public methods ensures implementation of principle of
encapsulation.
Access Modifiers in Python
Unlike C++ and Java, Python does not use the Public, Protected and Private keywords to specify
the type of access modifiers. By default, all the variables and methods in a Python class are public.
Example
Here, we have Employee class with instance variables name and age. An object of this class has
these two attributes. They can be directly accessed from outside the class, because they are public.
class Employee:
'Common base class for all employees'
def __init__(self, name="Bhavana", age=24):
[Link] = name
[Link] = age
e1 = Employee()
e2 = Employee("Bharat", 25)
print ("Name: {}".format([Link]))
print ("age: {}".format([Link]))
print ("Name: {}".format([Link]))
print ("age: {}".format([Link]))
It will produce the following output −
Name: Bhavana
age: 24
Name: Bharat
age: 25
Python doesn't enforce restrictions on accessing any instance variable or method. However, Python
prescribes a convention of prefixing name of variable/method with single or double underscore to
emulate behavior of protected and private access modifiers.
• To indicate that an instance variable is private, prefix it with double underscore (such as
"__age").
• To imply that a certain instance variable is protected , prefix it with single underscore
(such as "_salary").
Another Example
Let us modify the Employee class. Add another instance variable salary. Make age private
and salary as protected by prefixing double and single underscores respectively.
class Employee:
def __init__(self, name, age, salary):
[Link] = name # public variable
self.__age = age # private variable
self._salary = salary # protected variable
def displayEmployee(self):
print ("Name : ", [Link], ", age: ", self.__age, ", salary: ", self._salary)
e1=Employee("Bhavana", 24, 10000)
print ([Link])
print (e1._salary)
print (e1.__age)
When you run this code, it will produce the following output −
Bhavana
10000
Traceback (most recent call last):
File "C:\Users\user\[Link]", line 14, in <module>
print (e1.__age)
^^^^^^^^
AttributeError: 'Employee' object has no attribute '__age'
Python displays AttributeError because __age is private, and not available for use outside the class.
Name Mangling
Python doesn't block access to private data, it just leaves for the wisdom of the programmer, not to
write any code that access it from outside the class. You can still access the private members by
Python's name mangling technique.
Name mangling is the process of changing name of a member with double underscore to the
form object._class__variable. If so required, it can still be accessed from outside the class, but the
practice should be refrained.
In our example, the private instance variable "__name" is mangled by changing it to the format −
obj._class__privatevar
So, to access the value of "__age" instance variable of "e1" object, change it to
"e1._Employee__age".
Change the print() statement in the above program to −
print (e1._Employee__age)
It now prints 24, the age of e1.