In the previous chapetr we defined a decorator, like:
from take_time import timeit
Define a object
class Rectangle(object):
def __init__(self, s0, s1):
self.s0 = s0
self.s1 = s1
@timeit
def perimeter(self):
return 2 * (self.s0 + self.s1)
def area(self):
pass
square = Rectangle(5, 5)
square.perimeter()
Complete the class writing the method to compute the area... [2 minutes]
Define a new class for a circle: [5 minutes]
class Person(object):
def __init__(self, name, surname):
self.name = name.capitalize()
self.surname = surname.capitalize()
class Contact(Person):
def __init__(self, address=None, mobile=None, phone=None, *args, **kargs):
# super is a function that call the method of the parent object
super(Contact, self).__init__(*args, **kargs)
self.address = address
self.mobile = mobile
self.phone = phone
pietro = Person('pietro', 'zambelli')
pietro.name
zambelli = Contact(name='pietro', surname='zambelli', address='via Mesiano 77', phone='0461282696')
zambelli.phone
zambelli.name
zambelli
print zambelli
Define a new class that inherit from the Contact and return a beatiful output, definig the magic methods str, repr: [5 min]
class NiceContact(Contact):
def __init__(self):
pass
def __str__(self):
pass
def __repr__(self):
pass
Below you can find a test:
pietro = NiceContact(name='pietro', surname='zambelli', address='via Mesiano 77', phone='0461282696')
print repr(pietro) # use __repr__
print pietro # use __str__
Other magic methods
one = 1
two = 2.
one.__add__(2)
two.__sub__(one)
'a'.__add__('b') == 'a' + 'b'
phone='0461282696'
phone.isdigit()
See more magic mathods: http://www.rafekettler.com/magicmethods.html
class Contact(Person):
def _get_phone(self):
return self._phone
def _set_phone(self, phone):
if phone.isdigit():
if len(phone)>8:
self._phone = phone
else:
raise TypeError("Phone number must be longer than 8 characters")
else:
raise TypeError("Phone number must contain only numbers")
phone = property(fget=_get_phone, fset=_set_phone)
@property
def complete_name(self):
return "%s %s" % (self.name, self.surname)
def __init__(self, address=None, mobile=None, phone=None, *args, **kargs):
# super is a function that call the method of the parent object
super(Contact, self).__init__(*args, **kargs)
self.address = address
self.mobile = mobile
self.phone = phone
pietro = Contact(name='pietro', surname='zambelli', address='via Mesiano 77', phone='0461282696')
pietro.phone
pietro.phone = '045.'
pietro.complete_name
Using the string methods, modify the _set_phone
, to manage and clean string with strange characthers [2 min]
phone = '+39 046-128.26/96' # cleaned: '390461282696'