Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Python command issue

Posted on 2014-04-27
5
Medium Priority
?
377 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

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

Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
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.
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Suggested Courses

604 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