Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #40287

Re: need for help

Date 2013-03-01 14:58 -0500
From Dave Angel <davea@davea.name>
Subject Re: need for help
References <8B3DE2FF-3A5A-4666-8FF6-70B15AAF5987@icloud.com>
Newsgroups comp.lang.python
Message-ID <mailman.2752.1362167902.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 03/01/2013 01:35 PM, leonardo selmi wrote:
> hi guys
>
> i typed the following program:
>
> class ball:
>      def _init_(self, color, size, direction):
>          self.color = color
>          self.size = size
>          self.direction = direction
>
>      def _str_(self):
>          msg = 'hi, i am a ' + self.size + ' ' + self.color + 'ball!'
>          return msg
>
> myball = ball('red', 'small', 'down')
> print my ball
>
> BUT I GOT THIS ERROR:
>
> Traceback (most recent call last):
>    File "/Users/leonardo/Documents/ball2.py", line 11, in <module>
>      myball = ball('red', 'small', 'down')
> TypeError: this constructor takes no arguments
>
> can you kindly tell me what is wrong?
> thanks a lot!
>

1) please pick a useful subject line.  Every message "needs help".  But 
yours might be something like "constructor takes no arguments"

2) please tell us Python version you're targeting.  I'm assuming 2.7

3) Thank you for giving a full traceback error message.  Much better 
than an image file, or just paraphrasing, as many do. And thanks for 
posting as a text message, so your formatting doesn't get trashed.

When I run the program, I get:

davea@think2:~/temppython$ python leonardo.py
   File "leonardo.py", line 13
     print my ball
                 ^
SyntaxError: invalid syntax
davea@think2:~/temppython$


Which is caused by having a space in the middle of the myball variable.

After fixing that, I get your error, which is triggered by misspelling 
__init__    (you omitted one of the underscores at each end).

After fixing that, I get

davea@think2:~/temppython$ python leonardo.py
<__main__.ball instance at 0x7f330da5bbd8>
davea@think2:~/temppython$

which is triggered by the same error in the __str__ method.  These 
special methods are sometimes called dunder methods, because they all 
need double underscores, at both front and back.

davea@think2:~/temppython$ python leonardo.py
hi, i am a small redball!
davea@think2:~/temppython$


The other thing you should fix is the class definition line.  You forgot 
to derive your class from object, which makes your class an old style 
one, deprecated for many many years.  Doesn't matter here, but sooner or 
later it will.  And Python 3 supports only new-style classes, so you 
might as well be using them.

class ball(object):    #new style class


-- 
DaveA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: need for help Dave Angel <davea@davea.name> - 2013-03-01 14:58 -0500

csiph-web