0% found this document useful (0 votes)
12 views6 pages

Class Variables and Data Hiding in Python

The document discusses object-oriented programming concepts like classes, objects, class variables, instance variables, data hiding, and inheritance. It includes code examples showing: 1) Defining classes with class and instance variables and accessing them. 2) Creating hidden variables using double underscores and accessing them. 3) Using self or other keywords to reference class instances. 4) Modifying attributes inside classes. 5) Calling methods from parent and child classes.

Uploaded by

ali ahmed
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

Class Variables and Data Hiding in Python

The document discusses object-oriented programming concepts like classes, objects, class variables, instance variables, data hiding, and inheritance. It includes code examples showing: 1) Defining classes with class and instance variables and accessing them. 2) Creating hidden variables using double underscores and accessing them. 3) Using self or other keywords to reference class instances. 4) Modifying attributes inside classes. 5) Calling methods from parent and child classes.

Uploaded by

ali ahmed
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

March 27, 2019 Lab 04 – Class Variables and Data Hiding.

Student Name: Roll No: Section:

Lab Series No. 04.


Lab 04 –Class Variables and Data Hiding.

Lab Objectives:

1. Class and Instance Variables


2. Data Hiding
3. Self Parameter
4. Modification to attributes inside the class
1. Class and Instance Variables
In Python, instance variables are variables whose value is assigned inside a constructor or method with
self. Class variables are variables whose value is assigned in class.

Program 1: Write a Python program to create variable inside the class with string value and
accessing it.

Code:
# Python program to show that the variables with a value assigned in
class declaration, are class variables and variables inside methods
and constructors are instance variables.

# Class for Computer Science Student


class CSStudent:

# Class Variable
trade = 'Computer Science Software Engineering'

# The init method or constructor


def init (self, roll):

# Instance Variable
[Link] = roll

# Objects of CSStudent class


Faisal = CSStudent(315)
Farhan = CSStudent(316)

print([Link])
print([Link])
print([Link])
print([Link])

Prepared By CS-121 | Object Oriented 1


Programming
March 27, 2019 Lab 04 – Class Variables and Data Hiding.

Student Name: Roll No: Section:

# Class variables can be accessed using class name also


print([Link])

Program 2: Write a Python program to create instance variable inside method and accessing it.

Code:
# Python program to show that the variables with a value assigned in
class declaration, are class variables and variables inside methods
and constructors are instance variables.

# Class for Computer Science Student


class CSStudent:

# Class Variable
trade1 = 'Computer Science'
trade2 = 'Software Engineering'

# The init method or constructor


def init (self, roll):

# Instance Variable
[Link] = roll

# Adds an instance variable


def setAddress(self, address):
[Link] = address

# Retrieves instance variable


def getAddress(self):
return [Link]

# Objects of CSStudent class


Faisal = CSStudent(315)
[Link]("Gulistan e Johar")
print([Link]())

2. Data Hiding
In Python, we use double underscore (Or ) before the attributes name and those attributes will
not be directly visible outside.

Prepared By CS-121 | Object Oriented 2


Programming
March 27, 2019 Lab 04 – Class Variables and Data Hiding.

Student Name: Roll No: Section:


Program 3: Write a Python program which can create a hidden variable inside the class. Then try to
access it.

Code:

class MyClass:

# Hidden member of MyClass


hiddenVariable = 0

# A member method that changes


# hiddenVariable
def add(self, increment):
self. hiddenVariable += increment
print (self. hiddenVariable)

# Executing the Code


myObject = MyClass()
[Link](2)
[Link](5)

# This line causes error


print (myObject. hiddenVariable)

Program 4: Write a Python program which can create a hidden variable inside the class. Then try to
access it by using tricky method.

Code:

# A Python program to demonstrate that hidden


# members can be accessed outside a class
class MyClass:

# Hidden member of MyClass


hiddenVariable = 10

# Executing code
myObject = MyClass()
print(myObject._MyClass hiddenVariable)

Prepared By CS-121 | Object Oriented 3


Programming
March 27, 2019 Lab 04 – Class Variables and Data Hiding.

Student Name: Roll No: Section:


4. The Self Parameter
The self-parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.

It does not have to be named self, you can call it whatever you like, but it has to be the first
parameter of any function in the class:

Program 5: Write a Python program which use other than self keyword for reference .

Code:
class Person:
def init (a, name, age, salary, profession):
[Link] = name
[Link] = age
[Link] = salary
[Link] = profession

def mydetail(a):
print("Assalam o Alekum, my name is " + [Link] +", my age is
:" + str([Link]) +". Now a days earning :"+ str([Link]) + ", its
really lovely to be a " + [Link] )

person1 = Person("Syed Faisal Ali", 44, 1234567, "Research


Scientist")
[Link]()

Program 6: Write a Python program which can modify the attributes inside the class.

Code:
class Person:
def init (a, name, age, salary, profession):
[Link] = name
[Link] = age
[Link] = salary
[Link] = profession

def mydetail(a):
print("Assalam o Alekum, my name is " + [Link] +", my age is
:" + str([Link]) +". Now a days earning :"+ str([Link]) + ", its
really lovely to be a " + [Link] )

person1 = Person("Syed Faisal Ali", 42, 1234567, "Research


Scientist")
[Link]()

Prepared By CS-121 | Object Oriented 4


Programming
March 27, 2019 Lab 04 – Class Variables and Data Hiding.

Student Name: Roll No: Section:

print("Need to modify the age and salary inside the class")


[Link] = 44
[Link] = 7654321
[Link]()

Program 7: Write a Python program which uses the child class to call its own method and then parent
class method.

Code:

class Parent: # define parent class


parentAttr = 100
def init (self):
print ("Calling parent constructor")

def parentMethod(self):
print ('Calling parent method')

def setAttr(self, attr):


[Link] = attr

def getAttr(self):
print ("Parent attribute :", [Link])

class Child(Parent): # define child class


def init (self):
print ("Calling child constructor")

def childMethod(self):
print ('Calling child method')

c1 = Child() # instance of child


[Link]() # child calls its method
[Link]() # calls parent's method
[Link](200) # again call parent's method
[Link]() # again call parent's method

Prepared By CS-121 | Object Oriented 5


Programming
March 27, 2019 Lab 04 – Class Variables and Data Hiding.

Student Name: Roll No: Section:


Programming Exercise

Task1: Define what you understand by the classes, objects and functionalities for the following
scenarios.
Task 2: Make a class for insurance which can have multiple insurance policies. Design its UML and
Case diagram before coding. Later modify the attributes in child classes.
Task 3: Create a bike class and its components in light with the concept of Object Oriented. Later
create multiple bikes with different attributes based on customer requirements.

Task 7: You are working in Galaxy Computer as Programmer. The main business is selling computer,
laptops its accessories, used computer etc. Details can be find from [Link] Your task is
to analyze the website, define which classes will be require and create the complete program which
can take user name and its requirements then give the total amount of computer/ laptop or accessories.

Prepared By CS-121 | Object Oriented 6


Programming

Common questions

Powered by AI

In Python, data hiding is implemented with name mangling, which involves prefixing an attribute name with a double underscore `__` to make it private to the class. While direct access to these attributes is prevented, they can still be accessed using tricky methods by referencing the attribute with the class name prefix, such as `_ClassName__attribute`. For instance, accessing the hidden variable in `MyClass` can be done using `myObject._MyClass__hiddenVariable` .

Data hiding through private variables enhances program security and integrity by restricting direct access to crucial attributes, ensuring they can only be modified through defined methods, reducing chances of unintended interactions. This promotes encapsulation and increases the code's robustness. Nonetheless, it can also complicate maintenance and debugging, as accessing and modifying hidden variables becomes less straightforward, potentially requiring indirect methods or violating encapsulation principles for testing. Thus, while beneficial for security, it requires mindful implementation to balance accessibility and protection .

Effective management of modifications to class attributes can be achieved through several strategies: Using setter and getter methods helps encapsulate changes while maintaining control over the data. Implementing validation logic within these methods ensures that only acceptable values modify attributes. Utilizing design patterns like Observer can help synchronize attributes with an application's state or UI, triggering updates when changes occur. Furthermore, employing version control for classes allows reversible changes, making attribute management more secure and traceable. These strategies foster a controlled and responsive environment for handling attribute modifications dynamically .

To manage multiple insurance policies using OOP principles, a class called `Insurance` can be designed with attributes and methods specific to insurance policies. Subclasses can represent different types of insurance, each with unique attributes for that specific type, like `HealthInsurance`, `VehicleInsurance`, etc. A UML diagram should be created to design the relationships and interactions between these classes. By using encapsulation, each policy's attributes can be hidden, with public methods for interaction. This structure allows for scalable and efficient management by leveraging inheritance, polymorphism, and encapsulation .

In Python, the self parameter is a customary name for the first parameter of instance methods and refers to the object itself. It can be replaced with any name, as it is just a convention, not a requirement. For example, in the `Person` class, the self parameter is replaced with `a`, which retains its functionality for accessing and modifying object attributes. This change does not impact the method's functionality, as the parameter still acts as a reference to the current object .

The self parameter is critical in modifying attributes within a Python class as it provides access to the instance's current attributes and allows changes directly. This is demonstrated in the `Person` class, where the `init` method initializes attributes like name and age, and the `mydetail` method outputs them. The example further shows modifying `age` and `salary` attributes directly through an instance, i.e., `person1.age = 44`, `person1.salary = 7654321`, illustrating how the self parameter facilitates attribute modification .

Modeling a real-world business problem like selling computers and accessories can be done by creating classes that represent different aspects of the business. For instance, a `Product` class can be the super class with subclasses like `Computer`, `Laptop`, and `Accessory`. Each subclass can have specific attributes and methods pertinent to their context, such as specifications and pricing. A `Customer` class can manage customer-specific data and interactions, while a `Transaction` class can handle the sale process, compute totals, and manage receipts. This OOP approach allows encapsulation of each concept, reusability through inheritance, and dynamic behavior using polymorphism, effectively mirroring the business's operational structure .

Class variables in Python are variables with a value assigned within a class declaration and thus are shared among all instances of the class. They can be accessed using the class name or through any object of the class. In contrast, instance variables are defined within methods or constructors using `self`, meaning each instance of the class has its own copy. For example, in the CSStudent class, `trade` is a class variable while `roll` is an instance variable .

In Python, inheritance allows a child class to inherit methods and attributes of a parent class. This is demonstrated in the example where `Child` class inherits from `Parent`, enabling `Child` instances to call both its own `childMethod` and the `parentMethod` from `Parent`. The `Child` class reuses the parent's constructor and method, providing code reuse and modularity. Calling the `parentMethod` from a child instance exemplifies this reuse and illustrates the inheritance mechanism in Python OOP .

The benefits of using classes and objects in OOP include encapsulation of data, which keeps attributes and methods together, making management easier; inheritance, which allows for the creation of subclasses that share and extend the functionality of parent classes; and polymorphism, which provides the capability to define different behaviors for functions across various classes. OOP aligns well with real-world scenarios by organizing software around data principles. However, drawbacks include increased complexity, as designing proper class hierarchies and interactions requires careful planning, leading to the potential for overengineering. Real-world problems might not always fit neatly into an object-oriented model, sometimes complicating implementation .

You might also like