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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to