Solved

Python command issue

Posted on 2014-04-27
5
363 Views
Last Modified: 2014-05-21
I am running Python version 2.7.4.
I run this commands:
###
items = [37, 42]
items.__add__([73,101])
print items
###

The above prints [37, 42]. I was expecting [37, 42, 73,101]

Also I tried the following:
###
class Stack(object):
      def __init__(self): # Initialize the stack
            self.stack = [ ]
      def push(self,object):
            self.stack.append(object)
      def pop(self):
            return self.stack.pop()
      def length(self):
            return len(self.stack)

s = Stack() # Create a stack
s.push("Dave") # Push some things onto it
print s
s.push(42)
print s
s.push([3,4,5])
print s
x = s.pop() # x gets [3,4,5]
print s
y = s.pop() # y gets 42
print s
del s # Destroy s
###

I get the following output:
<__main__.Stack object at 0x02462850>
<__main__.Stack object at 0x02462850>
<__main__.Stack object at 0x02462850>
<__main__.Stack object at 0x02462850>
<__main__.Stack object at 0x02462850>

Could anyone please help me what I am doing wrong here?

Thanks a lot!
0
Comment
Question by:toooki
5 Comments
 
LVL 16

Assisted Solution

by:gelonida
gelonida earned 250 total points
ID: 40026671
add is the operation to add the current list with an other one and create a new one.

In other words __add__ implements the '+' operator and not the
'+=' operator. which would be done by calling __iadd_

so if you write
###
items = [37, 42]
c = items.__add__([73,101])
print items
print c
c = items.__iadd__([73,101])
print items
print c
###

Open in new window


you will see what I mean

Tou can look at following article who covers quite a lot of Python's amgic functions:
http://www.rafekettler.com/magicmethods.html
0
 
LVL 28

Accepted Solution

by:
pepr earned 250 total points
ID: 40026700
To add to gelonida's comment, you probably do not want to use __xxx__ methods when the object is used by the end user. They should always be treated as internal, important for implementation, but otherwise not expected to be used by the end user.

To be more explicit, you should prefer the
items = [37, 42]
items += [73,101]
print items

Open in new window

0
 

Author Comment

by:toooki
ID: 40026716
Thank you!

I was thinking that the above issues are related to Python version 2.7.4.  So I downloaded version 3.4.0.

But now no Python program is working.
###
#!/usr/bin/env python
import sys
print "hello"
###

The above gives error:
    print "hello"
                ^
SyntaxError: invalid syntax

Could you please comment. Thanks a lot.
0
 
LVL 37

Expert Comment

by:Gerwin Jansen
ID: 40026722
Where is your python installed? Check with:

which python

(you get a location), for example /bin/python

Then update your program like this: (put the correct location in there)

#!/bin/python
import sys
print "hello"
0
 
LVL 16

Expert Comment

by:gelonida
ID: 40026741
Fully agree with pepr:
Normally you should not call the 'magic' functions directly, but use their 'normal' representation like  '+' or '+='

They exist, so that you can overload them for special classes.


This leads to the second question that I overlooked

If you want to change the string representation of your stack class you can overload the
__str__() method

Example:
class Stack(object):
      def __init__(self): # Initialize the stack
            self.stack = [ ]
      def push(self,object):
            self.stack.append(object)
      def pop(self):
            return self.stack.pop()
      def length(self):
            return len(self.stack)
      def __str__(self):
            # just an example, use the formatting, that you like 
            return 'Stack<' + str(self.stack) + '>'

Open in new window


Concerning your python 3 version.


I'd recommend as first line in your script
#!/usr/bin/env python

On most Linux distributions this should call python2 by default if you have python2 and python3 installed.

If you want to be more explicit with the python version and even be save under some slightly weird Linux distros you can use:

#!/usr/bin/env/python2
or
#!/usr/bin/env python3

Many scripts can be written such, that they run under python2 and under python3

To make your above script portable you could do following:

#!/usr/bin/env python
# the next line (like ALL from __future__ . . . ) must be before any other
# pythion statement in yoru script

from __future__ import print_function

class Stack(object):
    . . . 


items = [37, 42]
items.__add__([73,101])
print(items)

Open in new window


The from __future__ import print_statement ensures, that python2 uses the same
syntax for print than python3,
# which means print is implemented now as a function and MUST thus be used with ()
# so print "hello" will fail whereas print("hello") will be OK.
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn how to get help with Linux/Unix bash shell commands. Use help to read help documents for built in bash shell commands.: Use man to interface with the online reference manuals for shell commands.: Use man to search man pages for unknown command…
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now