Python: Problem with overloaded constructors

2024/10/6 22:31:32

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 FileName Line Position Traceback Node31 exceptions.TypeError: this constructor takes no arguments

class Computer:name = "Computer1"ip = "0.0.0.0"screenSize = 17def Computer(compName, compIp, compScreenSize):name = compNameip = compIpscreenSize = compScreenSizeprintStats()returndef Computer():printStats()returndef printStats():print "Computer Statistics: --------------------------------"print "Name:" + nameprint "IP:" + ipprint "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objectsprint "-----------------------------------------------------"returncomp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)

Any thoughts?

Answer

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 andmembers.  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 nameslike __something__ often have special significance to the Pythoninterpreter.The first argument to any class method is a reference to the currentobject, called "self" by convention.You can use default function arguments instead of functionoverloading."""self.name = nameself.resolution = resolutionself.ip = ip# and so ondef printStats(self):"""You could instead use a __str__(self, ...) function to return thisstring.  Then you could simply do "print(str(computer))" if you wantedto."""print "Computer Statistics: --------------------------------"print "Name:" + self.nameprint "IP:" + self.ipprint "ScreenSize:" , self.resolution //cannot concatenate 'str' and 'tuple' objectsprint "-----------------------------------------------------"
https://en.xdnf.cn/q/70315.html

Related Q&A

Validate inlines before saving model

Lets say I have these two models:class Distribution(models.Model):name = models.CharField(max_length=32)class Component(models.Model):distribution = models.ForeignKey(Distribution)percentage = models.I…

Grouping and comparing groups using pandas

I have data that looks like:Identifier Category1 Category2 Category3 Category4 Category5 1000 foo bat 678 a.x ld 1000 foo bat 78 l.o …

Transform a 3-column dataframe into a matrix

I have a dataframe df, for example:A = [["John", "Sunday", 6], ["John", "Monday", 3], ["John", "Tuesday", 2], ["Mary", "Sunday…

python multiline regex

Im having an issue compiling the correct regular expression for a multiline match. Can someone point out what Im doing wrong. Im looping through a basic dhcpd.conf file with hundreds of entries such as…

OpenCV Python Bindings for GrabCut Algorithm

Ive been trying to use the OpenCV implementation of the grab cut method via the Python bindings. I have tried using the version in both cv and cv2 but I am having trouble finding out the correct param…

showing an image with Graphics View widget

Im new to qt designer and python. I want to created a simple project that I should display an image. I used "Graphics View" widget and I named it "graphicsView". I wrote these funct…

TemplateSyntaxError: settings_tags is not a valid tag library

i got this error when i try to run this test case: WHICH IS written in tests.py of my django application:def test_accounts_register( self ):self.url = http://royalflag.com.pk/accounts/register/self.c =…

Setting NLTK with Stanford NLP (both StanfordNERTagger and StanfordPOSTagger) for Spanish

The NLTK documentation is rather poor in this integration. The steps I followed were:Download http://nlp.stanford.edu/software/stanford-postagger-full-2015-04-20.zip to /home/me/stanford Download http:…

python variable scope in nested functions

I am reading this article about decorator.At Step 8 , there is a function defined as:def outer():x = 1def inner():print x # 1return innerand if we run it by:>>> foo = outer() >>> foo.…

How can I throttle Python threads?

I have a thread doing a lot of CPU-intensive processing, which seems to be blocking out other threads. How do I limit it?This is for web2py specifically, but a general solution would be fine.