Introduction to Python

davidbpython.com




In-Class Exercise Solutions, Session 10



CLASSES - INSTANCES AND METHODS

 
Ex. 10.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. 10.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. 10.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. 10.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. 10.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. 10.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. 10.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. 10.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. 10.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. 10.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)
 
Ex. 10.11 Demonstrate class attributes.

In the class below, set a class variable cvar to value 1000. Print the value of cvar in three places: 1) instance a (a.cvar); 2) instance b (b.cvar); 3) the class itself (Something.cvar) Also print the .attr attribute from each of the two instances.

Suggested Solution:
class Something:
    cvar = 1000                    # int, 1000

    def __init__(self, xx):        # self: 'Something' object; xx: int, 1000
        self.attr = xx             # int, 1000

a = Something('hi')                # 'Something' object
b = Something('there')             # 'Something' objects


print(a.cvar)                      # 1000
print(b.cvar)                      # 1000
print(Something.cvar)              # 1000

print(a.attr)                      # hi
print(b.attr)                      # there
 
Ex. 10.12 Create a class method.

Add a class method classincrement(cls) that uses its cls argument to increment the cattr class variable (cattr will be found to be an attribute of cls. Call classincrement() through the instance obj as well as through the class MyClass. The values printed below should both be 1. Before this can work as shown, however, you must decorate classincrement() with @classmethod.

Suggested Solution:
class MyClass:

    cattr = 0                            # int, 0

    @classmethod
    def classincrement(cls):             # cls:  'MyClass' class object
        cls.cattr = cls.cattr + 1        # int, 1

obj = MyClass()                          # 'MyClass' object


obj.classincrement()

print(obj.cattr)                         # 1
print(MyClass.cattr)                     # 1
 
Ex. 10.13 Create a static method.

To the below class add the static method ftoc(temp) which converts a temperature in Fahrenheit to Celcius. The formula is (temp - 32) * 5 / 9 To be a static method, the method must not take self as an argument, and must be decorated with @staticmethod.

Suggested Solution:
class Forecast:

    def __init__(self, forecast, high=0, low=0):   # self: 'Forecast' object; forecast: str; high: int, 62; low:  int, 48
        self.text = forecast                       # str, 'Light rain'
        self.hightemp = high                       # int, 62
        self.lowtemp = low                         # int, 48

    @staticmethod
    def ftoc(temp):                                # temp:  int, 32 (first call below)
        return (temp - 32) * 5 / 9                 # return 0


t = Forecast('Light rain', high=62, low=48)        #

print(t.ftoc(32))                                  # 0
print(t.ftoc(212))                                 # 100
 

LAB 2

 
Ex. 10.14 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. 10.15 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. 10.16 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
 
Ex. 10.17 Set a class variable, 'increment_value', that specifies how much the increment() method should increase the attribute. Add this value to the .counterval attribute in increment().
Suggested Solution:
class Counter:
    increment_value = 3                              # int, 3

    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 + Counter.increment_value       # int, 6


c = Counter(5)                                       # 'Counter' object

c.increment()
c.increment()

print(c.counterval)                                  # 5 + (2 * increment_value)
 
[pr]