Starting from:

$25

ITI1120-Lab 10 Objects Solved

(a)        What does the program below print? (Class Point is a simplified version of the class we designed in class). IMPORTANT: notice that the function riddle is outside of Point class (pay attention to what is lined up)

(b)        

 
 
 

http://www.pythontutor.com/visualize.html#mode

Open file t1.py  and copy it  in Python Vizualizer. Make sure  you understand what is happening  with variables as you step through the execution of the program.


(a)        What does the program below print? (Class Point is a simplified version of the class we designed in class)

(b)        

 
 
 

http://www.pythontutor.com/visualize.html#mode

Open file t2.py  and copy it  in Python Vizualizer. Make sure  you understand what is happening  with variables as you step through the execution of the program.


 

 

Introduction to Computing Using Python

Class methods (REVIEW)
A class method is really a function defined in the
lst = [9, 1, 8, 2, 7,  lst = [9, 1, 8, 2, 7, 3]3]

lst lst

[9[9, 1, 8, 2, 7, , 1, 8, 2, 7, 3]3]

 lst.sort()lst.sort()

lst lst

[1[1, 2, 3, 7, 8, , 2, 3, 7, 8, 9]9]

class namespace; when Python executes
 lst.instance.method(arg1, arg2, …)lst.instance.method(arg1, arg2, …)sort()sort()pppp nd(6)nd(6) it first translates it to

list.append(lclass.method(self, arg1, arg2, …)list.append(lclass.method(self, arg1, arg2, …)sorsor ((lstlst))t, 6)t, 6)

 and actually executes this last statement
The function has

an extra argument,         __add__    count

which is the object invoking the method

                                __add__()__add__()         count()count()

lst = [9, 1, 8, 2, 7,  lst = [9, 1, 8, 2, 7, 3]3]

lst lst

[9[9, 1, 8, 2, 7, , 1, 8, 2, 7, 3]3]  list.sort(lst)list.sort(lst)

lst lst

[1[1, 2, 3, 7, 8, , 2, 3, 7, 8, 9]9]

 lst.append(6)lst.append(6)

lst lst

[1[1, 2, 3, 7, 8, 9, , 2, 3, 7, 8, 9, 6]6]

 list.append(lst, 5)list.append(lst, 5)

lst lst

 [1[1, 2, 3, 7, 8, 9, 6, 5] , 2, 3, 7, 8, 9, 6, 5] pop x

. . . list

pop()pop() sort()sort()

Task 5: Methods class translation to Function calls

-           Open the file called t5.py and translate all the indicated method calls to equivalent  function calls

-           Once done run those function calls in Python shell to observe that they indeed are equivalent to their method call couterparts

Programming exercise 1:

 Open file lab10.py  It contains the classes we developed during lectures last week. Do the following exercises: 

A)        Add method distance to the class Point. It takes another Point object as input and returns the distance to that point (from the point invoking the method). (Recall that you need to import math to get sqrt function)

c = Point(0,1) 

d = Point(1,0)

c.distance(d) 

1.4142135623730951

B)         Add to class Point methods up, down, left, and right that move the Point object by 1 unit in the appropriate direction. The implementation of each should not modify instance variables x and y directly but rather indirectly by calling existing method move().

a = Point(3, 4) 

a.left() 

a.get() 

(2, 4)

C)         In  to class Animal modify the constructor to set age of the Animal object. Also add method getAge to  retrieve the age of the Animal object.

flipper = Animal('dolphin', '?', 3)

flipper.getAge()

3

                                                                                                                                                   Operator                                                                                                    Method

              Python operators             x + y        x.__add__(y)

x – y x.__sub__(y) x * y x.__mul__(y) x / y x.__truediv__(y)

In Python, all expressions involving operators 

are translated into method calls                                   x // y                      x.__floordiv__(y)

                     • (Recall that method invocations                         x % y         x.__mod__(y)

'!'.__mul__ '!'.__mul__ ' '!'*10!'*10            (10)(10)

'!!!!!!!!!!''!!!!!!!!!!'are then further translated to                                                                                                  x == y                            x.__eq__(y)

[1 [1,2,3].__eq__([2,,2,3].__eq__([2,function calls in a namespace) == [2,3,4] == [2,3,4]3,4])3,4])

FalseFalse                                      x != y                            x.__ne__(y)

 Built-in function TrueTrue int(2).__lt__ int(2).__lt__22 <  < 55 repr()(5)(5) returns the x y x.__gt__(y) canonical string representation 'a'.__le__('a' 'a'.__le__('a' <= 'a' <= 'a' )) of an object x = y x.__ge__(y)

TrueTrue

[1 [1len([1len([1,1,2,3,5,8].__len__,1,2,3,5,8].__len__• This is the representation printed by 11 22 33,,5,8])5,8])          ()()                    x < y              x.__lt__(y)

66        the shell when evaluating the object 

                                                                                                                                                                         x <= y                            x.__le__(y)

[1 [1repr([1,2,3])repr([1,2,3]),2,3].__repr__,2,3].__repr__()()                                          repr(x)                               x.__repr__()

[1'[1, 2, 3]'[1'[1, 2, 3]', 2, , 2, 3]3]

int(193).__repr__ int(193).__repr__repr(193)193repr(193)193                    ()()                   str(x)          x.__str__()

193'193’193'193’''

set().__repr__ set().__repr__rr pr(set())pr(set()) ()()                len(x)             x.__len__()

set()'set()'set()'set()'               <type(x) <type.__init__(x)

Introduction to Computing Using Python


Introduction to Computing Using Python Overloading repr()

In Python, operators are translated into method calls

To add an overloaded operator to a user-defined class, the corresponding method must be implemented

                                        a = Point(3,  a = Point(3, 4)4)             a = Point(3,  a = Point(3, 4)4)

  To get this behavior       a a a.__repr__ a.__repr__()() Point(3, 4)Point(3, 4)  Point(3, 4)Point(3, 4)

method __repr__() must be implemented and added to class Point __repr__() should return the (canonical) string representation of the point

class Point:class Point:

        # other Point methods here# other Point methods here

        def __repr__(self):def __repr__(self):

                 'canonical string representation Point(x, y)''canonical string representation Point(x, y)'                 return 'Point({}, {})'.format(self.x, self.y)return 'Point({}, {})'.format(self.x, self.y)

Introduction to Computing Using Python

Overloading operator +
                                                a = Point(3, a = Point(3,4)4)               a = Point(3, a = Point(3,4)4)

To get this behavior       b = Point(1, b = Point(1,2)2)   b = Point(1, b = Point(1,2)2)

  a+b a+b a.__add__(b a.__add__(b)) Point(4, 6)Point(4, 6) Point(4, 6)Point(4, 6)

method __add__() must be implemented and added to class Point

__add__() should return a new Point object whose coordinates are the sum of the coordinates of a and b   Also, method __repr__() should be implemented to achieve the desired display of the result in the shell
class Point:class Point:

        # other Point methods here# other Point methods here

        def __add__(self, point):def __add__(self, point):                 return Point(self.x+point.x, self.y+point.y)return Point(self.x+point.x, self.y+point.y)

        def __repr__(self):def __repr__(self):

                 'canonical string representation Point(x, y)''canonical string representation Point(x, y)'                 return 'Point({}, {})'.format(self.x, self.y)return 'Point({}, {})'.format(self.x, self.y)

                                                                                                                                                   Operator                                                                                                    Method

               str() vs repr()       x + y          x.__add__(y)

                                                                                                                                                                         x – y                            x.__sub__(y)

Built-in function __repr()__ returns the x * y x.__mul__(y) canonical string representation of an object

                                                                                                                                                                         x / y                        x.__truediv__(y)

•        This is the representation printed by x // y x.__floordiv__(y) the shell when evaluating the object

•         The string returned by __repr__ x % y x.__mod__(y) method must  look like the statement x == y x.__eq__(y) that creates that object x != y x.__ne__(y)

Built-in function __str()__ returns the                                                                                                  x y                             x.__gt__(y)

“pretty” string representation of an object                                                                                                 x = y                            x.__ge__(y)

•        This is the representation printed by x < y x.__lt__(y) the print() statement and is 

                                  meant to be readable by humans                                          x <= y        x.__le__(y)

str([1, str([1,[1print([1[1print([1,2,3].__str__,2,3].__str__2,3])2,3])2,3])2,3]) ()()                                          repr(x)                               x.__repr__()

[1'[1, 2, 3]'[1'[1, 2, 3]', 2, , 2, 3]3]

str strintprint(193)intprint(193)(193)(193).__str__().__str__()                                           str(x)                                x.__str__()

193'193''193'193 ’’

str(set str(setprint(set())print(set())etet )).__str__.__str__())())                ()()               len(x)             x.__len__()

set()'set()'set()'set()'               <type(x) <type.__init__(x)

Introduction to Computing Using Python

Programming exercise 2:

 Open file lab10.py.  It contains the classes we developed during lectures last week. Do the following exercises: 

Overload appropriate operators for class Card so that you can compare cards based on rank. In particular override  __gt__ , __ge__ , __lt__  and __le__

c1=Card('3','\u2660')

c2=Card('5','\u2662')

c1

Card(3,♠)

c2

Card(5, )♢

c1 < c2

True

c1 c2

False

c1<=c2

True

Programming exercise 3: Bank Account

Develop a class BankAccount that supports these methods:

•__init__:Initializes the bank account balance to the value of the input argument, or to 0 if no input argument is given

• withdraw: Takes an amount as input and withdraws it from the balance 

• deposit: Takes an amount as input and adds it to the balance • balance: Returns the balance on the account •__repr__: 

  x = BankAccount(700)  x = BankAccount(700) 

x.balance()  x.balance() 

700.00700.00  

x.withdraw x.withdraw(70)(70)

x.balance()  x.balance() 

630.00630.00  

x.deposit(7)  x.deposit(7) 

x.balance()  x.balance() 

637.00637.00

x x

BankAccount(637.00) BankAccount(637.00) 

Programming exercise 4: Ping Pong
 Write a class named PingPong that has a method next that alternates between printing ‘PING’ and ‘PONG’ as shown below.

  ball = PingPong ball = PingPong()()

ball.next ball.next()()

PINGPING

ball.next ball.next()()

PONGPONG

ball.next ball.next()()

PINGPING

ball.next ball.next()()

PONGPONG

Programming exercise 5a:  Class Queue
Goal: develop a class Queue , an ordered collection of objects that restricts insertions to the rear of the queue and removal from the front of the queue

•The class Queue should support methods:

•       Queue(): Constructor that initializes the queue to an empty queue

•       enqueue(item): Add item to the end of the queue

•       dequeue(): Remove and return the element at the front of the queue

•       isEmpty(): Returns True if the queue is empty, False otherwise

appts = Queue appts = Queue()()

appts.enqueue('John' appts.enqueue('John'))

  appts.enqueue('Annie' appts.enqueue('Annie'))

appts.enqueue('Sandy' appts.enqueue('Sandy'))

appts.dequeue appts.dequeue()()

'John''John'

appts.dequeue appts.dequeue()()

'Annie''Annie'

appts.dequeue appts.dequeue()()

'Sandy''Sandy'

appts.isEmpty appts.isEmpty()()

TrueTrue

Class Queue: example

                                                                     rearrear                rearrear   rear

 appts 'John''Annie' 'Annie''Sandy' 'Sandy'



 
 
 

front

appts = Queue appts = Queue()()

appts.enqueue('John' appts.enqueue('John'))

  appts.enqueue('Annie' appts.enqueue('Annie'))

appts.enqueue('Sandy' appts.enqueue('Sandy'))

appts.dequeue appts.dequeue()()

'John''John'

appts.dequeue appts.dequeue()()

'Annie''Annie'

appts.dequeue appts.dequeue()()

'Sandy''Sandy'

appts.isEmpty appts.isEmpty()()

TrueTrue

Programming exercise 5b: Class Queue

Make your class Queue user friendly by  adding to it __eq__, 

__repr__ and __len__

q1=Queue q1=Queue()()

              Example:           q1.enqueue('kiwi' q1.enqueue('kiwi'))

q1.enqueue('apple' q1.enqueue('apple'))

 print(q  print(q1)1)

print(q print(q1)1)

Queue(['kiwi', 'apple'])Queue(['kiwi', 'apple'])

len(q len(q1)1)

22

q2=Queue q2=Queue()()

q2.enqueue('apple' q2.enqueue('apple'))

q1==q q1==q22

FalseFalse

q1.dequeue q1.dequeue()()

'kiwi''kiwi'

q1==q q1==q22

TrueTrue

Programming exercise (Inheritance) 6: 

Class Vector

Implement a class Vector that supports the same methods as the class Point we developed in class. In other words it inherits all atributes (data and methods) from class Point. (Revisit class Animal and Bird to see a simple example)

The class Vector should also support vector addition and product operations. 

The addition of two vectors

v1 = Vector(1, 3) 

v2 = Vector(-2, 4)

is a new vector whose coordinates are the sum of the corresponding coordinates of v1 and v2:

v1 + v2

Vector(-1, 7)

The product of v1 and v2 is the sum of the products of the corresponding coordinates: 

v1 * v2

10 

In order for a Vector object to be displayed as Vector(., .) instead of Point(., .),you will need to override method __repr__().

Programming exercise 7a: Class Marsupial
Write a class named Marsupial that can be used as shown below:

m=Marsupial("red" m=Marsupial("red"))

m.put_in_pouch('doll' m.put_in_pouch('doll'))

m.put_in_pouch('firetruck' m.put_in_pouch('firetruck'))

m.put_in_pouch('kitten' m.put_in_pouch('kitten'))

m.pouch_contents m.pouch_contents()()

[['doll', 'firetruck', 'kitten''doll', 'firetruck', 'kitten']]

  print(m print(m)) I am a red Marsupial.I am a red Marsupial.

Programming exercise 7b (Inheritance) : Class Kangaroo  

Write a class named Kangaroo as a subclass of Marsupial that inherits all the attributes of Marsupial and also:    

•extends  the Marsupial 

__init__ constructor to take, as input, the coordinates x and y of the Kangaroo object,

•has method jump that takes number values dx and dy as input     and moves the kangaroo by dx units   along the x-axis and by dy units along   the y-axis, and

•overloads  the __str__ operator so  it behaves as shown below.

k = Kangaroo k = Kangaroo((""blueblue"", 0,0), 0,0)

print(k print(k))

I am a blue Kangaroo located atI am a blue Kangaroo located at  

coordinates (0,0)coordinates (0,0)

k.put_in_pouch('doll' k.put_in_pouch('doll'))

k.put_in_pouch('firetruck' k.put_in_pouch('firetruck'))

k.put_in_pouch('kitten' k.put_in_pouch('kitten'))

k.pouch_contents k.pouch_contents()()

[['doll', 'firetruck', 'kitten''doll', 'firetruck', 'kitten']]

k.jump(1, k.jump(1,0)0)

k.jump(1, k.jump(1,0)0)

k.jump(1, k.jump(1,0)0)

print(k print(k))

 I am a blue Kangaroo located atI am a blue Kangaroo located at  

coordinates (3,0)coordinates (3,0)

Programming exercise 8 : Class Points 

Write a class named Points (that represents points in the plane). The class has a list containing elements that are objects of type Point. 

 __init__ constructor creates an empty list if no input list is given. Otherwise it sets the list to the given list. 

•has method add(x,y) that adds an object Point with coordinates x and y to points

•has method left_most_point that returns the left most point in the set. If there is more than one left most it returns the bottom left most

•Has method  len and overrides __repr__

a=[Point(1,1), Point(1,2), Point(2,20), Point(1.5,  a=[Point(1,1), Point(1,2), Point(2,20), Point(1.5, -20)]-20)]

mypoints=Points(a mypoints=Points(a))

mypoints.add mypoints.add(1,-1)(1,-1)

mypoints.left_most_point mypoints.left_most_point()()

Point(1,-1)Point(1,-1)

len(mypoints len(mypoints))

55

mypoints mypoints

 Points([Point(1,1), Point(1,2), Point(2,20), Point(1.5,-20),Point(1,-1)])Points([Point(1,1), Point(1,2), Point(2,20), Point(1.5,-20),Point(1,-1)])

More products