Introduction to Python

davidbpython.com




In-Class Exercises, Session 13



CLASS ATTRIBUTES AND METHODS

 
Ex. 13.1 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.

class Something:
    # your class variable here

    def __init__(self, xx):
        self.attr = xx

a = Something('hi')
b = Something('there')


# print cvar in 3 places here

# print .attr from each of the two instances here
Expected Output:
1000
1000
1000
hi
there
 
Ex. 13.2 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.

class MyClass:
    cattr = 0

    # your classincrement(cls) method here


obj = MyClass()


obj.classincrement()

print(obj.cattr)          # should be 1
print(MyClass.cattr)      # should be 1
Expected Output:
1
1
 
Ex. 13.3 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.

class Forecast:

    def __init__(self, forecast, high=0, low=0):
        self.text = forecast
        self.hightemp = high
        self.lowtemp = low

    def ftoc(temp):
        return (temp - 32) * 5 / 9

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

print(t.ftoc(32))       # 0.0
print(t.ftoc(212))      # 100.0
Expected Output:
0.0
100.0
 

LAB 1

 
Ex. 13.4 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().
class Counter:
    # your class variable here

    def __init__(self, val):
        self.counterval = val

    def increment(self):
        self.counterval = self.counterval + 1
        # add the value of increment_value here

c = Counter(5)

c.increment()
c.increment()

print(c.counterval)    # 5 + (2 * increment_value)
Expected Output:
7
 
[pr]