Solved

Python command issue

Posted on 2014-04-27
5
366 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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
I. Introduction There's an interesting discussion going on now in an Experts Exchange Group — Attachments with no extension (http://www.experts-exchange.com/discussions/210281/Attachments-with-no-extension.html). This reminded me of questions tha…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:

770 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