0% found this document useful (0 votes)
1 views

OOPL 4thModule Methods

Uploaded by

hotelvlogger26
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

OOPL 4thModule Methods

Uploaded by

hotelvlogger26
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Variables

In Python, class variables (also known as class attributes) are shared across all instances
(objects) of a class. They belong to the class itself, not to any specific instance.
In Class, attributes can be defined into two parts:

 Class Variables/static: A class variable is a variable that is declared inside


of a Class but outside of any instance method or __init__() method.
 Instance variables: If the value of a variable varies from object to object,
then such variables are called instance variables.

Class Variable :
 If the value of a variable is not varied from object to object, such types of variables
are called class or static variables.

 All instances of a class share class variables. Unlike instance variable, the value of a
class variable is not varied from object to object,

 In Python, class variables are declared when a class is being constructed. They are not
defined inside any method of a class. Because of this, only one copy of the static
variable will be created and shared between all class objects.

For example, in the Student class, we can have different instance variables such as name
and roll number because each student’s name and roll number are different.But, if we want to
include the school name in the student class, we must use the class variable instead of an
instance variable because the school name is the same for all students. So, instead of
maintaining a separate copy in each object, we can create a class variable that will hold the
school name so all students (objects) can share it.
 You can use the class name or the instance to access a class variable.
 By convention, typically, it is placed right below the class header and before the
constructor method and other methods.
 Python Code

class Student:
# Class variable
class Student:
school_name = 'ABC School '
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
# create first object
s1 = Student('Emma', 10)
print(s1.name, s1.roll_no, Student.school_name)
# access class variable
# create second object
s2 = Student('Jessa', 20)
# access class variable
print(s2.name, s2.roll_no, Student.school_name)

 Recommended to use a class name to change the value of a class variable. Because if
we try to change the class variable’s value by using an object, a new instance variable
is created for that particular object, which shadows the class variables.
 If we modify the class variable in an instance, it will be modified in all the other
instances.

class Student:
# Class variable
school_name = 'ABC School '
# constructor
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
# create Objects
s1 = Student('Emma', 10)
s2 = Student('Jessa', 20)
print('Before')
print(s1.name, s1.roll_no, s1.school_name)
print(s2.name, s2.roll_no, s2.school_name)
# Modify class variable using object reference
Student.school_name = 'PQR School'
print('After')
print(s1.name, s1.roll_no, s1.school_name)
print(s2.name, s2.roll_no, s2.school_name)
Instance Variables :

 If the value of a variable varies from object to object, then such variables are called
instance variables.
 For every object, a separate copy of the instance variable will be created.
 Instance variables are not shared by objects. Every object has its own copy of the
instance attribute. This means that for each object of a class, the instance variable
value is different.
 We can access the instance variable using the object and dot (.) operator.
 In Python, to work with an instance variable and method, we use the self keyword.
We use the self keyword as the first parameter to a method. The self refers to the
current object.
 We use a constructor to define and initialize the instance variables. Let’s see the
example to declare an instance variable in Python.
 In the following example, we are creating two instance variable name and age in
the Student class.

 Python code

class Student:

# constructor
def __init__(self, name, age):
# Instance variable
self.name = name
self.age = age

# create first object


s1 = Student("Jessa", 20)
# access instance variable
print('Object 1')
print('Name:', s1.name)
print('Age:', s1.age)
# create second object
s2= Student("Kelly", 10)
# access instance variable
print('Object 2')
print('Name:', s2.name)
print('Age:', s2.age)

 When you change the instance variable’s values of one object, the changes will not be
reflected in the remaining objects because every object maintains a separate copy of
the instance variable.

Access Modifiers in Python


Access specifiers in Python have an important role to play in securing data from
unauthorized access and in preventing it from being exploited

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.

 By default, all the variables and methods in a Python class are public.
 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").

class Employee:
def __init__(self, name, age, salary):
self.name = name # public variable
self.__age = age # private variable
self._salary = salary # protected variable
def displayEmployee(self):
print ("Name : ", self.name, ", age: ", self.__age, ", salary: ", self._salary)
e1=Employee("Bhavana", 24, 10000)
print (e1.name)
print (e1._salary)
print (e1.__age)

Methods in python
These objects consist of properties and behavior. Furthermore, properties of the object are
defined by the attributes and the behavior is defined using methods. These methods in Python
are defined inside a class. These methods are the reusable piece of code that can be
invoked/called at any point in the program.

Instance method: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods.
 It must have a self parameter to refer to the current object.
 A instance method is bound to the object of the class.
 It can access or modify the object state by changing the value of a instance variables
 Python code

class Student:

# constructor

def __init__(self, name, age):

# Instance variable

self.name = name

self.age = age

# instance method access instance variable

def show(self):

print('Name:', self.name, 'Age:', self.age)

# create first object

print('First Student')
emma = Student("Jessa", 14)

# call instance method

emma.show()

Class Method:

 A class method is bound to the class and not the object of the class. It can
access only class variables.
 It can modify the class state by changing the value of a class variable that would
apply across all the class objects.
 The class method has a cls as the first parameter, which refers to the class.
 The class method can be called using ClassName.method_name() as well as by
using an object of the class.
 @classmethod decorator can be used in python for creating the class method.
Syntax of decorator classmethod() is as follows:
@classmethod

def fun(cls, arg1, arg2, …):

 python code

class Student:

# Class variable

school_name = 'ABC School '

def __init__(self, name, age):

self.name = name

self.age = age

@classmethod

def change_school(cls,name):

#print(Student.school_name)

#modify class variable


Student.school_name=name

def display(self):

print(self.name)

print(self.age)

print(Student.school_name)

Student.change_school('XYZ School')

jessa=Student('jessa',14)

tressa=Student('tresa',17)

jessa.display()

tressa.display()

Static method:
 A functionality that belongs to a class, but does not require the object, is placed in the
static method.
 Static methods does not receive any additional arguments like self, cls.
 .Static method knows nothing about the class and just deals with the parameters.
 Static method cannot access the properties of the class itself.
 When we need a utility function that doesn't access any properties of a class but
makes sense that it belongs to the class, we use static methods
 A static method can be called either on the class or on an instance.
 @staticmethod decorator can be used in python for creating the class method. Syntax of
decorator staticmethod() is as follows:

@staticmethod

def fun(arguments-optionals):

 python code
# Python program to
# demonstrate static methods
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a static method to check if a Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
# Driver's code
if _name__ == "__main__":
res = Person.isAdult(12)
print('Is person adult:', res)
res = Person.isAdult(22)
print('\nIs person adult:', res)

private method
 In Python, a private method is a method that is not intended to be used outside of the
class in which it is defined.
 These methods are denoted by a double underscore prefix (__) before their name, and
they can only be accessed within the class where they are defined
 These methods are used to implement internal functionality within the class. These
are not meant to be used by external code.
 Syntax
__method_name
 Python code
# Creating a class
class A:
# Declaring public method
def fun(self):
print("Public method")
# Declaring private method
def __fun(self):
print("Private method")
# Calling private method via
# another method
def Help(self):
self.fun()
self.__fun()
# Driver's code
obj = A()
obj.Help()
#obj.__fun()

You might also like