View Category
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom

Greeter("world").greet()

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
python

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
# required for Python 2.5 or less
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
python
#Start with the import statements.
import math # necessary to get the value of pi

class Shape(object):
"""Shape Class"""
def __init__(self):
"""Constructor method"""
pass #Do nothing here
def area(self):
"""The area method"""
pass #Do nothing here
def print_(self):
"""
The print method. Note the trailing underscore - this is because
there is a reserved statement called 'print' in python 2.x. The
trailing underscore is the accepted method of re-using names without
rebinding them
"""
print 'The name is: %s' % self.name #Print the only property we currently have

def _getName(self):
"""The getter method for the 'name' property.
Note that getter methods are generally discouraged in python"""
return self._name

_name = None # The leading underscore gives a weak non-public value
# to a variable. Two leading underscores will mangle its
# name at runtime, to make it more difficult to access.
# Note there is no real 'private' variable type in python.
name = property(_getName, doc='The name of this object')
# property statements work like: property(fget=None, fset=None, fdel=None, doc=None)

class Circle(Shape):
"""Circle Class - a sub class of shape"""
def __init__(self, radius, name='Circle'):
"""Constructor method again"""
Shape.__init__(self) # init the super class
self.radius = radius # Store the radius
self._setCircumference()# Function call
self._name = name

def _setCircumference(self):
self.circumference = 2*math.pi*self.radius

def area(self):
'''Return the area of this circle'''
tmpAera = math.pi * self.radius**2
return tmpAera
def print_(self):
'''The print method'''
super(Circle, self).print_() # This calls the print_ method in
# the super classes of Circle, in
# this case Shape
print 'The radius is: %f' % self.radius
print 'The circumference is %f' % self.circumference
print 'The area is: %f' % self.area()

class Rectangle(Shape):
"""The Rectangle Class"""
def __init__(self, length, breadth, name='Rectangle'):
Shape.__init__(self)
self._name = name
self.length = length
self.breadth = breadth
self.perimeter()
def area(self):
return self.breadth*self.length
def perimeter(self):
self._perimeter = self.breadth*2+self.length*2
return self._perimeter # You have a method return a value and still
# safely call it without handling the return
# value. This would be collected by garbage
# collection.
def print_(self):
super(Rectangle, self).print_()
print 'The length is %f and the breadth is %f' %(self.length, self.breadth)
print 'The perimeter is: %f' %self._perimeter
print 'The area is: %f' % self.area()

if __name__ == '__main__':
rectangle = Rectangle(5,3)
circle = Circle(5, name='Round and Round')
rectangle.print_()
circle.print_()

Implement and use an Interface

Create a Serializable interface consisting of 'save' and 'restore' methods, each of which:

* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types 'int' and 'string')

Next, create a Person class which has 'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
python
import pickle

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Name: {name}, age: {age}".format(name=self.name, age=self.age)


person = Person("Gaylord Focker", 21)
with open("person.pickle", "wb") as outstream:
pickle.dump(person, outstream)
with open("person.pickle", "rb") as instream:
deserialized_person = pickle.load(instream)
print(deserialized_person)