Python: Problem with overloaded constructors
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 // cannot concatenate 'str' and 'tuple' objects
print "-----------------------------------------------------"
return
comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
Any thoughts?
Asked by: Melissa510 | Posted: 28-01-2022
Answer 1
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 //cannot concatenate 'str' and 'tuple' objects
print "-----------------------------------------------------"
Answered by: Walter254 | Posted: 01-03-2022
Answer 2
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)
Answered by: Victoria288 | Posted: 01-03-2022
Answer 3
dude get yourself a python book. Dive into Python is pretty good.
Answered by: Madaline524 | Posted: 01-03-2022Answer 4
For a start, look here.
Answered by: John554 | Posted: 01-03-2022Answer 5
There are a number of things to point out:
- All instance methods in Python have an explicit self argument.
- Constructors are called
__init__
. - 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'
Answered by: Dainton348 | Posted: 01-03-2022
Answer 6
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)
Answered by: Justin934 | Posted: 01-03-2022
Answer 7
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.
Answered by: Fiona604 | Posted: 01-03-2022Answer 8
Python does not support function overloading.
Answered by: Chester576 | Posted: 01-03-2022Similar questions
python - Cython and overloaded c++ constructors
Is there a standardized (or commonly accepted way) to tackle the issue of not being able to overload __cinit__ methods in cython when wrapping C++ classes?
There is the possibility of making __cinit__ take *args and **kwargs to contain parameters and inside the __cinit__ scope select the way to generate the C++ instance according to certain pattern. This approach however has c...
PythonWin's python interactive shell calling constructors twice?
While answering Static class variables in Python
I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice?
PythonWin 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright infor...
How to handle constructors or methods with a different set (or type) of arguments in Python?
Is there a way in Python, to have more than one constructor or more than one method with the same name, who differ in the number of arguments they accept or the type(s) of one or more argument(s)?
If not, what would be the best way to handle such situations?
For an example I made up a color class. This class should only work as a basic example to discuss this, there is lo...
python - What is a clean "pythonic" way to implement multiple constructors?
I can't find a definitive answer for this. As far as I know, you can't have multiple __init__ functions in a Python class. So how do I solve this problem?
Suppose I have a class called Cheese with the number_of_holes property. How can I have two ways of creating cheese objects...
One that takes a number of holes like this: parmesan = Cheese(num_holes = 15)
How do derived class constructors work in python?
I have the following base class:
class NeuralNetworkBase:
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
self.inputLayer = numpy.zeros(shape = (numberOfInputs))
self.hiddenLayer = numpy.zeros(shape = (numberOfHiddenNeurons))
self.outputLayer = numpy.zeros(shape = (numberOfOutputs))
self.hiddenLayerWeights = numpy.zeros(shape = (numberOfInputs...
Is it not possible to define multiple constructors in Python?
This question already has answers here:
python - Multiple inheritance in django. Problem with constructors
I have a model like this:
class Person(models.Model,Subject):
name = ..
The class Subject is not supposed to be in the Database so, it doesn't extends from models.Model:
class Subject:
def __init__(self,**kargs):
_observers = []
my problem is that the constructor of Subject is never called, so i've tried adding this to the ...
Differences Between Python and C++ Constructors
I've been learning more about Python recently, and as I was going through the excellent Dive into Python the author noted here that the __init__ method is not technically a constructor, even though it generally functions like one.
I have two questions:
python - lxml objectify does not call constructors for custom element classes
lxml.objectify does not seem to call the constructors for my custom element classes:
from lxml import objectify, etree
class CustomLookup(etree.CustomElementClassLookup):
def lookup(self, node_type, document, namespace, name):
lookupmap = { 'custom' : CustomElement }
try:
return lookupmap[name]
except KeyError:
return None
class CustomElement(etree.Eleme...
python - How to mock objects with constructors in Python3?
I'm new to Python (I'm from Java) and I'm facing an issue in using mocks in Python3.2.
Here is the code:
import gzip
class MyClass:
_content = None
_gzipfile = gzip.GzipFile
def __init__(self, content):
self._content = content
def my_method(self):
# Code ...
gzipper = self._gzipfile(fileobj=data)
return gzipper.read()
import unittest
from mo...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python