Introduction to Python
davidbpython.com
Project Warmup Exercise Solutions, Session 10
Ex. 10.1 | Create a class called ThisClass, with one method, report(self). Inside this method, the instance/object (which is labeled self) should call the special id() function to report its own reference id, i.e. print id(self). Create three instances using the constructor (for example, a = ThisClass()) and then call the report() method on each of them. |
class ThisClass(object):
def report(self):
print(id(self))
a = ThisClass()
b = ThisClass()
c = ThisClass()
a.report()
b.report()
c.report()
print()
print(id(a))
print(id(b))
print(id(c))
|
|
Ex. 10.2 | Create a class, TimeStamp(object): that can store the current timestamp in an instance attribute. |
import datetime
class TimeStamp(object):
def set_time(self):
self.t = str(datetime.datetime.now())
def get_time(self):
return self.t
var1 = TimeStamp()
var2 = TimeStamp()
var1.set_time()
var2.set_time()
print(var1.get_time())
print(var2.get_time())
print()
var1.set_time()
print(var1.get_time())
print(var2.get_time())
|
|
Ex. 10.3 | Copy the above code, and this time replace the set_time() method with the constructor, __init__(self). |
import datetime
class TimeStamp(object):
def __init__(self):
self.t = str(datetime.datetime.now())
def get_time(self):
return self.t
var1 = TimeStamp()
var2 = TimeStamp()
print(var1.get_time())
print(var2.get_time())
print()
print(var1.get_time())
print(var2.get_time())
|
|