?
Solved

Python command issue

Posted on 2014-04-27
5
Medium Priority
?
376 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 17

Assisted Solution

by:gelonida
gelonida earned 1000 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 29

Accepted Solution

by:
pepr earned 1000 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 38

Expert Comment

by:Gerwin Jansen, EE MVE
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 17

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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

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…
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 the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
Suggested Courses
Course of the Month14 days, 15 hours left to enroll

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