• The Python tutorials are written as Jupyter notebooks and run directly in Google Colab—a hosted notebook environment that requires no setup. Click the Run in Google Colab button.


  • Colab link - Open colab


  • # Python Classes and 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.


  • Create a Class: To create a class, use the keyword **class**.


  •  
    class MyClass:
      x = 5
    
     
    
  • Create an Object:** Now we can use the class named myClass to create objects.


  •  
    p1 = MyClass()
    print(p1.x)         
    #Create an object named p1, and print the value of x
     
    
  • The __init__() Function: The examples above are classes and objects in their simplest form, and are not really useful in real life applications.


  • To understand the meaning of classes we have to understand the built-in __init__() function.


  • All classes have a function called __init__(), which is always executed when the class is being initiated.


  • Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.


  •  
    class Person:
      def __init__(self, name, age,address):
        
        self.age = age
        self.name = name
        self.address = address
    
    p1 = Person("John",45,"mumbai")
    
    print(p1.name)
    print(p1.age)
    print(p1.address)
     
    
  • Create a class named Person, use the __init__() function to assign values for name and age.


  • NOTE:** The __init__() function is called automatically every time the class is being used to create a new object.


  • Object Methods:** Objects can also contain methods. Methods in objects are functions that belongs to the object.


  • Let us create a method in the Person class.


  •  
    class Person:
      def __init__(self, name, age):
        self.name = name
        self.age = age
    
      def myfunc(self):
        print("Hello my name is " + self.name)
        print(self.age-6)
    
    p1 = Person("John", 36)
    p1.myfunc()
     
    
  • Insert a function that prints a greeting, and execute it on the p1 object.


  • NOTE:** The self parameter is a reference to the class instance itself, and is used to access variables that belongs to the class.


  • Exercise 1** Write a Python class to convert an integer to a roman numeral.


  •  
    
    class py_solution:
        def int_to_Roman(self, num):
            val = [
                1000, 900, 500, 400,
                100, 90, 50, 40,
                10, 9, 5, 4,
                1
                ]
            syb = [
                "M", "CM", "D", "CD",
                "C", "XC", "L", "XL",
                "X", "IX", "V", "IV",
                "I"
                ]
            roman_num = ''
            i = 0
            while  num > 0:
                for _ in range(num // val[i]):
                    roman_num += syb[i]
                    num -= val[i]
                i += 1
            return roman_num
    
    
    print(py_solution().int_to_Roman(1))
    print(py_solution().int_to_Roman(4000))
    
    
     
    
  • Exercise 2** Write a Python class to convert a roman numeral to an integer.


  •  
    
    class py_solution:
        def roman_to_int(self, s):
            rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
            int_val = 0
            for i in range(len(s)):
                if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
                    int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
                else:
                    int_val += rom_val[s[i]]
            return int_val
    
    print(py_solution().roman_to_int('MMMCMLXXXVI'))
    print(py_solution().roman_to_int('MMMM'))
    print(py_solution().roman_to_int('C'))
    
     
    
  • Exercise 3** Write a Python class to get all possible unique subsets from a set of distinct integers. Input : [4, 5, 6] Output : [[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]


  •  
    
    class py_solution:
        def sub_sets(self, sset):
            return self.subsetsRecur([], sorted(sset))
        
        def subsetsRecur(self, current, sset):
            if sset:
                return self.subsetsRecur(current, sset[1:]) + self.subsetsRecur(current + [sset[0]], sset[1:])
            return [current]
    
    print(py_solution().sub_sets([4,5,6]))
    
    
     
    
  • Exercise 4** Write a Python class to find the three elements that sum to zero from a set of n real numbers.


  •  
    
    
    class py_solution:
     def threeSum(self, nums):
            nums, result, i = sorted(nums), [], 0
            while i < len(nums) - 2:
                j, k = i + 1, len(nums) - 1
                while j < k:
                    if nums[i] + nums[j] + nums[k] < 0:
                        j += 1
                    elif nums[i] + nums[j] + nums[k] > 0:
                        k -= 1
                    else:
                        result.append([nums[i], nums[j], nums[k]])
                        j, k = j + 1, k - 1
                        while j < k and nums[j] == nums[j - 1]:
                            j += 1
                        while j < k and nums[k] == nums[k + 1]:
                            k -= 1
                i += 1
                while i < len(nums) - 2 and nums[i] == nums[i - 1]:
                    i += 1
            return result
    
    print(py_solution().threeSum([-25, -10, -7, -3, 2, 4, 8, 10]))
    
    
    
     
    
  • Exercise 5** Write a Python class to implement pow(x, n).


  •  
    
    class py_solution:
       def pow(self, x, n):
            if x==0 or x==1 or n==1:
                return x 
    
            if x==-1:
                if n%2 ==0:
                    return 1
                else:
                    return -1
            if n==0:
                return 1
            if n<0:
                return 1/self.pow(x,-n)
            val = self.pow(x,n//2)
            if n%2 ==0:
                return val*val
            return val*val*x
    
    print(py_solution().pow(2, -3));
    print(py_solution().pow(3, 5));
    print(py_solution().pow(100, 0));
    
    
    
     
    
  • Exercise 6 ** Write a Python class to reverse a string word by word. Input string : 'hello .py' Expected Output : '.py hello'


  •  
    
    class py_solution:
        def reverse_words(self, s):
            return ' '.join(reversed(s.split()))
    
    
    print(py_solution().reverse_words('hello .py'))
    
    
    
     
    
  • Exercise 7** Write a Python class which has two methods get_String and print_String. get_String accept a string from the user and print_String print the string in upper case.


  •  
    class IOString():
        def __init__(self):
            self.str1 = ""
    
        def get_String(self):
            self.str1 = input()
    
        def print_String(self):
            print(self.str1.upper())
    
    str1 = IOString()
    str1.get_String()
    str1.print_String()
    
    
    
     
    
  • Exercise 8** Write a Python class named Rectangle constructed by a length and width and a method which will compute the area of a rectangle.


  •  
    
    class Rectangle():
        def __init__(self, l, w):
            self.length = l
            self.width  = w
    
        def rectangle_area(self):
            return self.length*self.width
    
    newRectangle = Rectangle(12, 10)
    print(newRectangle.rectangle_area())
    
    
    
     
    
  • Exercise 9** Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.


  •  
    class Circle():
        def __init__(self, r):
            self.radius = r
    
        def area(self):
            return self.radius**2*3.14
        
        def perimeter(self):
            return 2*self.radius*3.14
    
    NewCircle = Circle(8)
    print(NewCircle.area())
    print(NewCircle.perimeter())
    
    
    
     
    
  • Exercise 10** Write a Python class named Temperature and a method which take temperature input into celcius and print in Fehrenheit.


  •  
    
    class Temprature():
      def  convertFahrenhiet(self,celsius):
        return (celsius*(9/5))+32
    
    
    
     
    
  • Exercise 11** Write a Python class named Temperature and a method which take temperature input into Fehrenheit and print in Celcius.


  •  
    
    class Temperature():
     def convertCelsius(self,farenhiet):
        return (farenhiet-32)*(5/9)
    
    
    
     
    
  • Exercise 12** Create a Circle class and intialize it with radius. Make two methods getArea and getCircumference inside this class.


  •  
    
    class Circle():
      def __init__(self,radius):
        self.radius = radius
      def  getArea(self):
        return 3.14*self.radius*self.radius
      def getCircumference(self):
        return self.radius*2*3.14
      
    
    
    
     
    
  • Exercise 13** Create a Student class and initialize it with name and roll number. Make methods to : 1. Display - It should display all informations of the student. 2. setAge - It should assign age to student 3. setMarks - It should assign marks to the student.


  •  
    
    class Student():
      def __init__(self,name,roll):
        self.name = name
        self.roll= roll
      def display(self):
        print self.name
        print self.roll
      def setAge(self,age):
        self.age=age
      def setMarks(self,marks):
        self.marks = marks
      
    
    
    
     
    
  • Exercise 14** Create a Time class and initialize it with hours and minutes. 1. Make a method addTime which should take two time object and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min) 2. Make a method displayTime which should print the time. 3. Make a method DisplayMinute which should display the total minutes in the Time. E.g.- (1 hr 2 min) should display 62 minute.


  •  
    
    class Time():
    
      def __init__(self, hours, mins):
        self.hours = hours
        self.mins = mins
    
      def addTime(t1, t2):
        t3 = Time(0,0)
        if t1.mins+t2.mins > 60:
          t3.hours = (t1.mins+t2.mins)/60
        t3.hours = t3.hours+t1.hours+t2.hours
        t3.mins = (t1.mins+t2.mins)-(((t1.mins+t2.mins)/60)*60)
        return t3
    
      def displayTime(self):
        print "Time is",self.hours,"hours and",self.mins,"minutes."
    
      def displayMinute(self):
        print (self.hours*60)+self.mins
    
    a = Time(2,50)
    b = Time(1,20)
    c = Time.addTime(a,b)
    c.displayTime()
    c.displayMinute()
    
    
    
     
    
  • Exercise 15** Create a python class which model banking transaction of withdrawing an amount.


  •  
    
    class BankAccount:
        def __init__(self):
            self.balance = 0
    
        def withdraw(self, amount):
            self.balance -= amount
            return self.balance
    
    a = BankAccount()
    b = BankAccount()
    
    a.withdraw(100)
    b.withdraw(50)
    
    
     
    
  • Exercise 16** Create a python class which model banking transaction of depositing an amount.


  •  
    
    class BankAccount:
        def __init__(self):
            self.balance = 0
     def deposit(self, amount):
            self.balance += amount
            return self.balance
    
    a = BankAccount()
    b = BankAccount()
    
    a.deposit()
    b.deposit()