Home > database >  How to get inputs to properly work with classes, Python
How to get inputs to properly work with classes, Python

Time:05-03

As of now I am wondering how to get inputs into a class.

class Contact:

    def __init__(self, name = "",strengthPts = 0, power = ""):
        self.name = name
        self.power = power
        self.strengthPts = strengthPts

    def addStrengthPts(self, points):

        self.strengthPts = self.strengthPts   points
    
def main():

    namequestion = raw_input("put in a name")
    time.sleep(1)
    powerquestion = raw_input("What power would you like?")
    
    newContact = Contact(namequestion , powerquestion)
    
    print("The fabulous superhero, "   newContact.name)
    time.sleep(1)
    print(newContact.name   "'s superpower is "   newContact.power )
    print(newContact.power)


main()  

my output is

The fabulous superhero, test
test's superpower is

My main problem, (on the bottom of the output) is that the power's input is not relaying. I am not sure if this is a simple mistake with how I added it to my "newContact" or a problem with how inputs work with classes.

CodePudding user response:

Your class' initializer is defined with three positional arguments (def __init__(self, name = "",strengthPts = 0, power = ""):). However, in this example you've passed two (newContact = Contact(namequestion , powerquestion)) which would mean that you're setting the value of powerquestion to your class instance's strengthPts instance variable. Since you've elected not to pass the power argument, it will use the default value of a blank string ("").

Either pass a value for the strengthPts positional variable, or use a named argument for power:

newContact = Contact(namequestion, power=powerquestion)
  • Related