Unit 5 5marks

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

UNIT-V ( 5Marks )

1. Discuss the concept of a class.

A class specifies the set of instance variables and methods that are “bundled
together” for defining a type of object. Class is a blueprint or template to define an
object. Attributes are the names given to the variables that make up a class.

A class instance with a defined set of properties is called an object. As a result, the
same class can be used to construct as many objects as needed.

Let’s define a class named Book for a bookseller’s sales software.

class Book:
def __init__(self, title, quantity, author, price):
self.title = title
self.quantity = quantity
self.author = author
self.price = price

The __init__ special method, also known as a Constructor, is used to initialize the
Book class with attributes such as title, quantity, author, and price.

In Python, built-in classes are named in lower case, but user-defined classes are
named in Camel or Snake case, with the first letter capitalized.

This class can be instantiated to any number of objects. Three books are instantiated
in the following example code:

book1 = Book('Book 1', 12, 'Author 1', 120)


book2 = Book('Book 2', 18, 'Author 2', 220)
book3 = Book('Book 3', 28, 'Author 3', 320)

book1, book2 and book3 are distinct objects of the class Book. The term self in the
attributes refers to the corresponding instances (objects).

print(book1)
print(book2)
print(book3)
Output:

<__main__.Book object at 0x00000156EE59A9D0>


<__main__.Book object at 0x00000156EE59A8B0>
<__main__.Book object at 0x00000156EE59ADF0>

The class and memory location of the objects are printed when they are printed. We
can't expect them to provide specific information on the qualities, such as the title,
author name, and so on. But we can use a specific method called __repr__ to do
this.
In Python, a special method is a defined function that starts and ends with two
underscores and is invoked automatically when certain conditions are met.

class Book:
def __init__(self, title, quantity, author, price):
self.title = title
self.quantity = quantity
self.author = author
self.price = price

def __repr__(self):
return f"Book: {self.title}, Quantity: {self.quantity}, Author: {self.author}, Price:
{self.price}"

book1 = Book ('Book 1', 12, 'Author 1', 120)


book2 = Book ('Book 2', 18, 'Author 2', 220)
book3 = Book ('Book 3', 28, 'Author 3', 320)

print(book1)
print(book2)
print(book3)

Output:

Book: Book 1, Quantity: 12, Author: Author 1, Price: 120


Book: Book 2, Quantity: 18, Author: Author 2, Price: 220
Book: Book 3, Quantity: 28, Author: Author 3, Price: 320
2. Explain the use of subclasses with examples.

Inheritance, in object-oriented programming, is the ability of a class to inherit


members of another class as part of its own definition. The inheriting class is called a
subclass (also “derived class” or “child class”), and the class inherited from is called
the superclass (also “base class” or “parent class”). Superclasses may themselves
inherit from other classes, resulting in a hierarchy of classes.

Class A is the superclass of all the classes in the figure. Thus, subclasses B
and E each inherit variable var1 and method method1 from Class A. In addition,
Class B defines variable var2 and method method2, and Class E defines method5.
Since Class C is a subclass of Class B, it inherits everything in Class A and Class B,
adding var3 and method3 in its own definition. And since Class D is also a subclass
of Class B, it inherits everything in Class A and Class B, also defining method4.

3. Write down the set data type in Python.

The Set Data Type in Python:

A set is a mutable data type with nonduplicate, unordered values, providing


the usual mathematical set operations. One of the most commonly used set
operators is the in operator (which we have been already using with sequences) for
determining membership,

>>> fruit = {'apple', 'banana', 'pear', 'peach'}

>>> fruit

{'pear', 'banana', 'peach', 'apple'}

>>> 'apple' in fruit

True
Sets do not maintain a logical ordering. Therefore, it is invalid and makes no sense
to access an element of a set by index value.

The add and remove methods allow sets to be dynamically altered during program
execution, for example,

>>>fruit. add ('pineapple')


>>>fruit
{'pineapple', 'pear', 'banana', 'peach', 'apple'}
To define an initially empty set, or to initialize a set to the values of a particular
sequence, the set constructor is used,

>>>set1 = set() >>>vegs = ['peas', 'corn'] >>>vowels = 'aeiou'

>>>len(set1) >>>set(vegs) >>>set(vowels)

0 {'corn', 'peas'} {'a', 'i', 'e', 'u', 'o'}

In the above example, to create an empty an empty set1, the notation set () is
used, since empty braces is used to create an empty dictionary. Because sets do not
have duplicate elements, adding an already existing item to a set results in no
change to the set.

Let us write a Python program to create a new empty set.

#Create a new empty set.

x= set ()

print (x)

# Create a non empty set.

n= set ([0, 1, 2, 3, 4])

print (n)

Output:

set()

{0, 1, 2, 3, 4}

>>>
Set Types

There are currently two built-in set types,

1. set type-

The set type is mutable---the contents can be changed using methods like
add() and remove(). Since it is mutable, it has no hash value and cannot be used as
either a dictionary key or as an element of another set.

2. frozenset type: The frozenset type is immutable and hashable ---its contents
cannot be altered after it is created; however, it can be used as a dictionary key or as
an element of another set.

Thus, all its members are declared when it is defined,

Example:

>>> apple_colors = frozenset(['red', 'yellow', 'green'])

As shown in the above example, the values of a set of type frozenset must be
provided in a single list when defined. (A frozenset type is needed when a set is
used as a key value in a given dictionary.)

4. Develop a fraction class for demon starting motion of encapsulation.

The Fraction object shows private instance variables __numerator and


__denominator, and four public methods. Private members of a class begin with two
underscore characters, and cannot be directly accessed. For example, trying to
access the instance variables of Fraction object frac1 is invalid,

frac1. numerator = 4 NOT ALLOWED

frac1.denominator= 6 NOT ALLOWED

Public members of a class, on the other hand, are directly accessible. For
example, the following are valid method calls,
frac1.getNumerator() ALLOWED
frac1.getDenominator() ALLOWED
frac1.setNumerator(4) ALLOWED
frac1.setDenominator(6) ALLOWED
These methods are referred to as getters and setters since their purpose is to
get (return) and set (assign) private instance variables of a class. Restricting access
to instance variables via getter and setter methods allows the methods to control
what values are assigned (such as not allowing an assignment of 0 to the
denominator), and how they are represented when retrieved. Thus, the instance
variables of a class are generally made private, and the methods of the class
generally made public.

Defining a Fraction Class:

The first stage in the development of a Fraction class is given.

The class keyword is used to define classes, much as def is used for defining
functions. All lines following the class declaration line are indented. Instance
variables are initialized in the __init__ special method. Being private, instance
variables __numerator and __denominator are not meant to be directly accessed.

>>> frac1.__numerator

AttributeError: 'Fraction' object has no attribute '__numerator'

In actuality, however, private members are accessible if written as follows:

>>>frac1._Fraction__numerator

class Fraction (object):

def init(self, numerator, denominator):

"""Inits Fraction with values numerator and denominator."""

self.__numerator = numerator

self.__ denominator = denominatur

self.reduce()

def getNumerator (self):

"""returns the numerator of a Fraction."""

return self._numerator
def getDenominator (self):

"""returns the denominator of a Fraction."""

return self._denominator

def setNumerator (self, value):

"""Sets the numerator of a Fraction to the provided value."""

self.__numerator - value

def setDenominator (self, value):

"""Sets the denominator of a Fraction to the provided value.

Raises a ValueError exception if a value of zero provided.

"""

if value == 0:

raise ValueError('Divide by Zero Error")

self. denominator -value

To understand this, all private class members are automatically renamed to begin
with a single underscore character followed by the class name. Such renaming of
identifiers is called name mangling. Unless the variable or method is accessed with
its complete (mangled) name, it will not be found. Name mangling prevents
unintentional access of private members of a class, while still allowing access when
needed.

The methods of a class, as we have seen, are essentially functions meant to


operate on the instance variables of the class. In Python, functions serving as a
method must have an extra first parameter, by convention named self. This
parameter contains a reference to the object instance to which the method belongs.
When a method accesses any other member of the same class, the member name
must be preceded by 'self' (self.__numerator). Getter and setter methods are also
defined. Note that setDenominator raises an exception when passed a value of 0 to
ensure that Fraction objects cannot be set to an invalid value. We further discuss
special methods in Python next.

You might also like