Introduction to Python

davidbpython.com




In-Class Exercise Solutions, Session 12



CLASSES - INSTANCES AND METHODS

 
Ex. 12.1 Define a class.

Use the class statement with name MyClass (or you may substitute a name of your own choice). To fill the otherwise empty block, use the pass statement. Initialize an instance of the class and print its type to show that it is an instance of the class.

Suggested Solution:
class MyClass:
    pass

x = MyClass()         # 'MyClass' object
print(type(x))        # <class 'MyClass'>
 
Ex. 12.2 Create an 'instance' method.

Add to the class Hola below a new method, saludar(), that prints "bienvenidos a todos" (or whatever greeting you'd prefer) when it is called.

Suggested Solution:
class Hola:
    """ una clase que is amigable """
    def saludar(self):                       # self: 'Hola' object
        print('bienvenidos a todos')

yo = Hola()                                  # 'Hola' object

yo.saludar()                                 # should print the greeting
 
Ex. 12.3 Add argument and return value to method.

Add the method doubleit() below, that doubles the value passed to it.

Suggested Solution:
class Numbers:
    """ various number methods """
    def doubleit(self, val):              # self: 'Numbers' object; val: int, 5 (1st call below)
        return val * 2                    # return 10

num = Numbers()                           # 'Numbers' object
val = num.doubleit(5)                     # int, 10
print(val)

val2 = num.doubleit(100)                  # int, 200
print(val2)
 

LAB 1

 
Ex. 12.4 Create a class Time that has a method get_time() that returns the current time. Call as shown.

(A string showing the current time can be obtained from the time module using time.ctime().)

Suggested Solution:
import time

class Time:
    def get_time(self):        # self: 'Time' object (obj)
        return time.ctime()    # str of the current time


obj = Time()                   # 'Time' object
print(obj.get_time())          # should show the current time
 
Ex. 12.5 Create a class Random that has a method get_rand(val) that returns a random number from 1 to the specified value. Call as shown.

(A random number can be generated with random.randint(x, y) where x and y are the minimum and maximum values.)

Suggested Solution:
import random

class Random:
    def get_rand(self, val):           # self: 'Random' object; val:  int, 5 (first call below)
        return random.randint(1, val)  # return randomly chosen integer between 1-5

obj = Random()                         # 'Random' object

val = obj.get_rand(5)                  # int, random from 1-5
print(val)

val2 = obj.get_rand(18)                # int, random from 1-18
print(val2)
 
Ex. 12.6 Create a class Math with method add() that takes two integer arguments and returns the values summed.
Suggested Solution:
class Math:
    def add(self, val, val2):        # self: 'Math' object; val: int, 5; val2: int, 10 (first call below)
        return val + val2            # return 10

obj = Math()                         # 'Math' object

mysum = obj.add(5, 10)               # int, 15
print(mysum)

mysum2 = obj.add(100, 150)           # int, 250
print(mysum2)
 

CLASSES - CONSTRUCTOR, CLASS ATTRIBUTES AND METHODS

 
Ex. 12.7 Demonstration: note the unique identifier of self and an instance from a class.

At the bottom of the code below, print obj, then call obj.something(), noting that this method prints self. Compare the hex codes that identify the instance. Next, print obj2 and call obj2.something(), and note the output, particularly the hex codes.

Suggested Solution:
class Do:
    def something(self):        # self: 'Do' object
        print(self)


obj = Do()                      # 'Do' object
obj2 = Do()                     # 'Do' object

print(obj)
obj.something()
print()

print(obj2)
obj2.something()
 
Ex. 12.8 Create an __init__() method.

Add a method to the below class, __init__(self) that inside the function announces and prints the argument self, i.e. print(f'self: {self}'). Construct 2 new instances, and then print each instance. Put a blank line between each instance.

Suggested Solution:
class Be:
    """ this class is something! """
    def __init__(self):                     # self: 'Be' object
        print(f'self:    {self}')


obj1 = Be()                                 # 'Be' object
print(f'object:  {obj1}')

print()

obj2 = Be()                                 # 'Be' object
print(f'object:  {obj2})
 
Ex. 12.9 Set an instance attribute in __init__().

Create a method __init__(self, num) that sets numin self as a .value attribute. At bottom, print obj.value to see the value.

Suggested Solution:
class Live:
    """ a class that just wants to live """
    def __init__(self, num):                       # self: 'Live' object; num: int 5
        self.value = num                           # int, 5


obj = Live(5)                                      # 'Live' object

print(obj.value)                                   # 5
 
Ex. 12.10 Create a "getter" method.

Create a method get_value() that returns the .value attribute from the instance.

Suggested Solution:
class Say:
    def __init__(self, val):        # self: 'Say' object; val: int, 100
        self.value = val            # int, 100

    def get_value(self):            # self: 'Say' object
        return self.value           # return 100


obj = Say(100)                      # 'Say' object

vl = obj.get_value()                # int, 100
print(vl)
 

LAB 2

 
Ex. 12.11 Create class Counter, initialized with an integer as shown below. Set the attribute .counterval in __init__ so that it is available in the instance.
Suggested Solution:
class Counter:
    def __init__(self, val):         # self: 'Counter' object; val: int, 5
        self.counterval = val        # int, 5

c = Counter(5)                       # 'Counter' object

print(c.counterval)                  # 5
 
Ex. 12.12 Update Counter with an .increment() method that increments the attribute value each time it is called. Call .increment() twice, then print the value of .counterval through the instance.
Suggested Solution:
class Counter:
    def __init__(self, val):                   # self: 'Counter' object; val: int, 5
        self.counterval = val                  # int, 5

    def increment(self):                       # self: 'Counter' object
        self.counterval = self.counterval + 1  # int, 6


c = Counter(5)                                 # 'Counter' object

c.increment()
c.increment()

print(c.counterval)                            # 7
 
Ex. 12.13 Update Counter with a show_value() method that returns the attribute value.
Suggested Solution:
class Counter:
    def __init__(self, val):                    # self: 'Counter' object; val: int, 5
        self.counterval = val                   # int, 5

    def increment(self):                        # self: 'Counter' object
        self.counterval = self.counterval + 1   # int, 6 (1st call below)

    def show_value(self):                       # self: 'Counter' object
        return self.counterval                  # return 7


c = Counter(5)

c.increment()
c.increment()

print(c.counterval)                             # 7
 
[pr]