How do you write this in python

Jeff Shannon jeff at ccvcorp.com
Wed Oct 6 19:52:02 EDT 2004


Ali wrote:

>ok that makes some sense.
>
>  
>
>>You can assign properties whenever you want - it does not have to be 
>>done in the __init__ method.
>>    
>>
>
>This cought my attention so I entered this into the shell to try to do
>this very thing:
>
>  
>
>>>>class card:
>>>>        
>>>>
>      def setProperties(self, name, email):
>         self.name = name
>         self.email = email
>      def show(self):
>         print self.name + '/' + self.email
>
>  
>
>>>>ali = card('ali','ali at ali.com')
>>>>        
>>>>
>
>I got the following error:
>
>Traceback (most recent call last):
>  File "<pyshell#27>", line 1, in ?
>    ali = card('ali','ali at ali.com')
>TypeError: this constructor takes no arguments
>
>I thought you said I could assign the properties at any place so I
>defined them in the setProperties() method. What did I do wrong?
>  
>

You can assign attributes whenever you want (and what you're doing is 
setting attributes; properties are something special, and different).

However, when you create a new object by calling the class constructor, 
__init__() is the only function that will be automatically called.  If 
you don't define __init__(), then (in essence) Python will use a dummy 
__init__() that takes only self as an argument, and does nothing.  
However, you've tried to pass several arguments to __init__(), but you 
didn't define your own...

The class you've defined can't be created with name or email attributes, 
since you haven't provided an __init__() to catch them.  However, you 
can create a 'blank' card and then add the name and email later.

 >>> ali = card('ali', 'ali at ali.com')
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: this constructor takes no arguments
 >>> ali = card()
 >>> ali.setProperties('ali', 'ali at ali.com')
 >>> ali.show()
ali/ali at ali.com
 >>>

Jeff Shannon
Technician/Programmer
Credit International






More information about the Python-list mailing list