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
Solved

Python command issue

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

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 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 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

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

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

Linux users are sometimes dumbfounded by the severe lack of documentation on a topic. Sometimes, the documentation is copious, but other times, you end up with some obscure "it varies depending on your distribution" over and over when searching for …
Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
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…

860 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