Jomonsugi
Jomonsugi

Reputation: 1279

Assign a value to object passed into class if value is null

I am having trouble figuring out how to assign a value if no value is assigned to the object I am passing into this class.

I know this code looks a bit convoluted, but I wrote it as an example to answer my question.

The class simply assigns a numerical value to each letter in a string passed in as an object. Then pairs.generate will print the number associated with whatever letter is given. If a letter is given that is not in the dictionary created, it returns 0. Thus, if the dictionary is empty, 0 will be output for any letter given.

What I want to do is output a 0 if no object is passed in, but instead I receive the following error: TypeError: init() takes exactly 2 arguments (1 given)

To see what is working, pass the string "ABCD" in as an object and change the letter passed to pairs.generate(). To demonstrate what I want to happen when no object is passed, pass an empty string in (""). This will output 0 which is what I want to happen when no object is passed in instead of receiving the error message.

class Pairs(object):
def __init__(self, letters):
    print letters
    counter = 1
    d = {}
    for x in letters:
        d[x] = counter
        counter +=1

    self.d = d
    print self.d
    pass

def generate(self, letter):
    print "this is the key", letter
    if letter not in self.d:
        print "this key isn't in the dictionary:", letter
        return 0
    else:
        print "this is the value", self.d[letter]
        return self.d[letter]


enter = Pairs()
print enter.generate("F")

Edit I have tried passing a default argument from my understanding. I tried a few ideas along the lines of:

class Plugboard(object):
    if object is None:
       object = ""

However, I am continuing to receive the same error.

Upvotes: 0

Views: 84

Answers (1)

user2682863
user2682863

Reputation: 3218

You need to either explicitly pass the argument required by your init method or add a default argument to init. Here is an example with the default argument included

class Pairs(object):
    def __init__(self, letters=""):  # added default value for letters
        print (letters)
        counter = 1
        d = {}
        for x in letters:
            d[x] = counter
            counter += 1

        self.d = d
        print(self.d)
        pass # this doesn't do anything

    def generate(self, letter):
        print ("this is the key", letter)
        if letter not in self.d:
            print ("this key isn't in the dictionary:", letter)
            return 0
        else:
            print ("this is the value", self.d[letter])
            return self.d[letter]


enter = Pairs() # this calls __init__, should pass 'letters'
print (enter.generate("F"))

Upvotes: 1

Related Questions