[Tutor] Constructs

Alan Gauld alan.gauld at btinternet.com
Tue Apr 8 10:20:53 CEST 2014

On 08/04/14 06:40, Santosh Kumar wrote:
>    1 #!/usr/bin/python
>    2
>    3 class shape:
>    4   def __init__(self,x,y):
>    5     self.x = x
>    6     self.y = y
>    7   description = "This shape has not been described yet"
>    8   author = "Nobody has claimed to make this shape yet"
>    9
>   10   def __init__(self,x,y,z):
>   11     self.x = x
>   12     self.y = y
>   13     self.z = z
>   14   print "The values are %d,%d,%d" %(self.x,self.y,self.z)
>   15
>   16 triangle = shape(100,20,30)
>   17 rectange = shape(20,30)
> I am getting NameError exceptions when i am trying to achieve these.
>   python third.py
> Traceback (most recent call last):
>    File "third.py", line 3, in <module>
>      class shape:
>    File "third.py", line 14, in shape
>      print "The values are %d,%d,%d" %(self.x,self.y,self.z)
> NameError: name 'self' is not defined

> can we have two constructs within the same class. My requiment is very
> simple, when i want to pass two values the shape class should take two
> arguments and when i pass on three it should take 3 arguments . Is this
> possible ?

No, its not possible in Python, there is no overloading of methods.

The normal way to accept variable numbers of parameters is to use 
default values

def __init__(self, a, b, c=None):
     if c is None:
        # do one thing
        # do another

But in your case you should probably be defining subclasses since 
triangle and rectangle are probably going to need different method
implementations for most things.

The name error however is nothing to do with that.
The problem there is that you have put the print statement
outside of the method so it gets executed during class definition.
At that stage there is no instance and therefore no self value.
I suspect you wanted to have it indented to the same
level as the self assignment lines?

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list