Thursday, May 18, 2023

#PYTHON(DAY22)OOPS(Inheritance)

 

#PYTHON(DAY22)

object oriented programming(Inheritance)

In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind the data and the functions that work on that together as a single unit so that no other part of the code can access this data.

Main Concepts of Object-Oriented Programming (OOPs)

  • Class
  • Objects
  • Polymorphism
  • Encapsulation
  • Inheritance
  • Data Abstraction
oops

we have already discussed about the class and objects in the previous story, now let us continue with the other concepts

Inheritance

Inheritance is the capability of one class to derive or inherit the properties from another class. The class that derives properties is called the derived class or child class and the class from which the properties are being derived is called the base class or parent class. The benefits of inheritance are:

  • It represents real-world relationships well.
  • It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.
  • It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.

Types of Inheritance –

Single Inheritance:
Single-level inheritance enables a derived class to inherit characteristics from a single-parent class.

Example:

class parent:
px = 10 # static attribute
def parentMethod1(self):
print('This is method one from parent class')
class child(parent):
def childMethod1(self):
print('This is method one from child class')
p = parent()
c = child()
print(c.parentMethod1(),c.px)

And the output is:

This is method one from parent class
None 10

Multilevel Inheritance:
Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class.

Example:

class Gp:
def gpMethod(self):
print('Gp\'s method')
class P(Gp):
def parentMethod(self):
print('p\'s method')
class C(P):
def childMethod(self):
print('c\'s method')
x = C()
print(C.mro())

And the output is:

[<class '__main__.C'>, <class '__main__.P'>, <class '__main__.Gp'>, <class 'object'>]

Hierarchical Inheritance:
Hierarchical level inheritance enables more than one derived class to inherit properties from a parent class.

Example:

class P:
def pm(self):
print('this is a parent method')

class C1(P):
def c1m(self):
print('this is a child1 method')


class C2(P):
def c2m(self):
print('this is a child2 method')
C1.__mro__

And the output is:

(__main__.C1, __main__.P, object)

Multiple Inheritance:
Multiple level inheritance enables one derived class to inherit properties from more than one base class.

Example:

class Parent_1:
def parent1method(self):
print('this is from parent1')

class Parent_2:
def parent2method(self):
print('this is from parent2')
class Child(Parent_1,Parent_2):
pass
child = Child()
print(child.parent1method(),child.parent2method())

And the output is:

this is from parent1
this is from parent2
None None

Wednesday, May 17, 2023

#PYTHON(DAY21)instance,static attributes and methods

 

#PYTHON(DAY21)

instance attributes

  • object level attribute
  • these may or may not have the same values across all objects
  • in above example, the crust,oil etc can have different values for different objects, these can be considered as instance attributes
class Foo:
def __init__(self, a, b):
self.a = a
self.b = b
x1,x2 = Foo(10,20), Foo(11,22)
print((x1.a,x1.b), (x2.a,x2.b), sep = '\n')

And the output is:

(10, 20)
(11, 22)

static attributes

  • static variable remains common for the entire class
  • the user can change according to his requirement
class Rest:
disc = 0
def __init__(self,bill):
self.bill = bill


def totalBill(self):
return self.bill-(self.bill*self.disc)
a1 = Rest(50)
print(a1.totalBill())

a2 = Rest(50)
a2.disc = 0.10
a2.totalBill()

And the output is:

50
45.0

methods

instance methods

  • these methods take self as first parameter, we use these methods to modify or alter the instance’s attributes or state
  • in dictionary from keys is a class method and all are instance methods.
  • instance method acts on object, attributes changes on object level

class methods

  • these methods accepts ‘cls’ as their first attribute, we define a class method by using a decorator @classmethod
  • class method acts on class level
  • using class method we can alter class attributes

static methods

  • we define static methods using @staticmethod decorator, these methods accept no cls or self as first parameter
  • it does not work on class or object
class Rest:
disc = 0
def __init__(self,bill):
self.bill = bill

def printBill(self):
print(f'bill before discount is {self.bill}')

@classmethod
def discount(cls):
print(f'the discount you availed is{cls.disc} %')
#print(f'total bill to paidmpost discount is {self.})
@staticmethod
def greet():
print('welcome')
Rest.discount()

# using the object
a1 = Rest(50)
a1.printBill()
a1.discount() # we can also access class attribute by using object without self

And the output is:

the discount you availed is0 %
bill before discount is 50
the discount you availed is0 %
a1.greet()
Rest.greet()

And the output is:

welcome
welcome
class student1():
y = 60
def details(self,name,rollno,study,sec,totalmarks):
self.n = name
self.r = rollno
self.a = study
self.sec = sec
self.m = totalmarks

def cutoff(self):
if self.m>=self.y:
print('pass')
else:
print('fail')
def over(self):
print((f'''student name is {self.n} rollno:{self.r} belongs to {self.a}class section {self.sec} total marks are {self.m}'''))
ab = student1()
ab.details('xyz',456,7,'a',50)
ab.cutoff()
ab.over()
fail
student name is xyz rollno:456 belongs to 7class section a total marks are 50

Tuesday, May 16, 2023

#PYTHON(DAY20)


Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
Hello my name is John

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

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:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()
Hello my name is John

Modify Object Properties

You can modify properties on objects like this:

Example

Set the age of p1 to 40:

p1.age = 40
40

Delete Object Properties

You can delete properties on objects by using the del keyword:

Example

Delete the age property from the p1 object:

del p1.age
Traceback (most recent call last):
File "demo_class7.py", line 13, in <module>
print(p1.age)
AttributeError: 'Person' object has no attribute 'age'

Delete Objects

You can delete objects by using the del keyword:

del p1
Traceback (most recent call last):
File "demo_class8.py", line 13, in <module>
print(p1)
NameError: 'p1' is not defined 


Monday, May 15, 2023

#PYTHON(DAY19)class and object,_init_(),_str_() functions

 

#PYTHON(DAY19)

classes and objects

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a “blueprint” for creating objects.

syntax

class classname():
pass

creating object of a class

Now, we can use class name to create a object

x = classname()
print(type(x))

Example

class sample:
x=5
print(sample)

And the output is:

<class '__main__.sample'>
y = sample()
print(y.x)

And the output is:

5

The __init__() Function

  • init: is a special method, with a clear and definite functionality to assign values to our object properties and methods that might require these values, and in whole are require to create an object
  • note class functions that start with’__’ are called as special methods. They executes a pre-defined functionality.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

And the output is:

John
36

The __str__() Function

The __str__() function controls what should be returned when the class object is represented as a string.

If the __str__() function is not set, the string representation of the object is returned:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)

And the output is:

John(36)

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...