views:

2195

answers:

9

WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!

I have written the following code, however I get the following exception:

Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments

class Computer:

    name = "Computer1"
    ip = "0.0.0.0"
    screenSize = 17


    def Computer(compName, compIp, compScreenSize):
        name = compName
        ip = compIp
        screenSize = compScreenSize

        printStats()

        return

    def Computer():
        printStats()

        return

    def printStats():
        print "Computer Statistics: --------------------------------"
        print "Name:" + name
        print "IP:" + ip
        print "ScreenSize:" + screenSize
        print "-----------------------------------------------------"
        return

comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)

Any thoughts?

+5  A: 

Constructors in Python are called __init__. You must also use "self" as the first argument for all methods in your class, and use that to set instance variables in the class.

class Computer:

    def __init__(self, compName = "Computer1", compIp = "0.0.0.0", compScreenSize = 22):
        self.name = compName
        self.ip = compIp
        self.screenSize = compScreenSize

        self.printStats()

    def printStats(self):
        print "Computer Statistics: --------------------------------"
        print "Name:", self.name
        print "IP:", self.ip
        print "ScreenSize:", self.screenSize
        print "-----------------------------------------------------"


comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
truppo
printStatus has a bug: it doesn't declare self.
Pramod
Ha! Jinx! We entered the same solution.
Brian C. Lane
Thanks for your help, it worked a treat! I really suppose I should have read a tutorial before diving in!
TK
+1  A: 

That isn't valid python.

The constructor for a Python class is def __init__(self, ...): and you cannot overload it.

What you can do is use defaults for the arguments, eg.

class Computer:
    def __init__(self, compName="Computer1", compIp="0.0.0.0", compScreenSize=17):
        self.name = compName
        self.ip = compIp
        self.screenSize = compScreenSize

        self.printStats()

        return

    def printStats(self):
        print "Computer Statistics: --------------------------------"
        print "Name      : %s" % self.name
        print "IP        : %s" % self.ip
        print "ScreenSize: %s" % self.screenSize
        print "-----------------------------------------------------"
        return

comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
Brian C. Lane
+2  A: 

For a start, look here.

ayaz
+2  A: 

There are a number of things to point out:

  1. All instance methods in Python have an explicit self argument.
  2. Constructors are called init.
  3. You cannot overload methods. You can achieve a similar effect by using default method arguments.

C++:

class comp  {
  std::string m_name;
  foo(std::string name);
};

foo::foo(std::string name) : m_name(name) {}

Python:

class comp:
  def __init__(self, name=None):
    if name: self.name = name
    else: self.name = 'defaultName'
Pramod
Can you tell that I'm a c# programmer?!
TK
+1  A: 

Ah, these are common gotchas for new python developers.

First, the constructor should be called:

__init__()

Your second issue is forgetting to include the self parameter to your class methods.

Furthermore, when you define the second constructor, you're replacing the definition of the Computer() method. Python is extremely dynamic and will cheerfully let you redefine class methods.

The more pythonic way is probably to use default values for the parameters if you don't want to make them required.

Dana
+22  A: 

I'm going to assume you're coming from a Java-ish background, so there are a few key differences to point out.

class Computer(object):
    """Docstrings are used kind of like Javadoc to document classes and
    members.  They are the first thing inside a class or method.

    You probably want to extend object, to make it a "new-style" class.
    There are reasons for this that are a bit complex to explain."""

    # everything down here is a static variable, unlike in Java or C# where
    # declarations here are for what members a class has.  All instance
    # variables in Python are dynamic, unless you specifically tell Python
    # otherwise.
    defaultName = "belinda"
    defaultRes = (1024, 768)
    defaultIP = "192.168.5.307"

    def __init__(self, name=defaultName, resolution=defaultRes, ip=defaultIP):
        """Constructors in Python are called __init__.  Methods with names
        like __something__ often have special significance to the Python
        interpreter.

        The first argument to any class method is a reference to the current
        object, called "self" by convention.

        You can use default function arguments instead of function
        overloading."""
        self.name = name
        self.resolution = resolution
        self.ip = ip
        # and so on

    def printStats(self):
        """You could instead use a __str__(self, ...) function to return this
        string.  Then you could simply do "print(str(computer))" if you wanted
        to."""
        print "Computer Statistics: --------------------------------"
        print "Name:" + self.name
        print "IP:" + self.ip
        print "ScreenSize:" + self.resolution
        print "-----------------------------------------------------"
Paul Fisher
The answer of the day. Clear, efficient, realistic.
e-satis
+2  A: 

dude get yourself a python book. Dive into Python is pretty good.

Ankur Gupta
Yeah I realise this now ... as I can't get an actual book for at least another 16 hours, I thought that I'd dive right in ... after all "how difficult can it be?!"
TK
Find an on-line book. Here's one: http://homepage.mac.com/s_lott/books/python.html
S.Lott
+1  A: 

Python does not support function overloading.

Eden
A: 

...thanks Paul. Your answer was complete, and it answered some other questions that I had.

Good work!

agentv