jiahuiding jiahuiding - 1 month ago 6
Python Question

How to create the __init__ function?

This is the instructions:

1.Define a class named Bag in a module named bag.py

2.Define an init method that has one parameter, an iterable of values that initalize the bag. Writing Bag() constructs an empty bag. Writing Bag(['d','a','b','d','c','b','d']) construct a bag with one 'a', two 'b's, one 'c', and three 'd's. Objects in the Bag class should store only the dictionary specified above: it should not store/manipulate any other self variables

from collections import defaultdict
from goody import type_as_str
from test.test_string import Bag

class Bag:
def __init__(self, i):
if len(i) == 0:
self.bag = []
for x in i:
self.bag.append(x)




if __name__ == '__main__':
#driver tests
import driver
driver.default_file_name = 'bsc1.txt'
# driver.default_show_exception= True
# driver.default_show_exception_message= True
# driver.default_show_traceback= True
driver.driver()


This is the Error I got:

7 # Test init, repr, and str
8 *Error: b = Bag() raised exception TypeError: __init__() missing 1 required positional argument: 'i'
9 *Error: repr(b) in ['Bag()','Bag([])'] raised exception NameError: name 'b' is not defined
10 *Error: str(b) raised exception NameError: name 'b' is not defined
11 *Error: b = Bag(['d','a','b','d','c','b','d']) raised exception AttributeError: 'Bag' object has no attribute 'bag'
12 *Error: all((repr(b).count('\''+v+'\'')==c for v,c in dict(a=1,b=2,c=1,d=3).items())) raised exception NameError: name 'b' is not defined
13 *Error: all((v+'['+str(c)+']' in str(b) for v,c in dict(a=1,b=2,c=1,d=3).items())) raised exception NameError: name 'b' is not defined


The input is:

# Test init, repr, and str
c-->b = Bag()
e-->repr(b) in ['Bag()','Bag([])']-->True
e-->str(b)-->Bag()
c-->b = Bag(['d','a','b','d','c','b','d'])
e-->all((repr(b).count('\''+v+'\'')==c for v,c in dict(a=1,b=2,c=1,d=3).items()))-->True
e-->all((v+'['+str(c)+']' in str(b) for v,c in dict(a=1,b=2,c=1,d=3).items()))-->True


I have no idea how to make the init function. since the first input calls b = Bag(), whcih will always raise Error: b = Bag() raised exception TypeError: init() missing 1 required positional argument. Can anyone tell me how to fix it?

Answer

Your init method is expecting the argument i to be initialize, And another problem of your code is self.bag will never initialize to a list if len(i) is not zero, you can,t append to bag if its not define as list before hand. Code below should fit what you want

class Bag:
    def __init__(self, i=None):
        self.bag = []
        if i == None:
            pass # i is None, do nothing after create empty bag
        elif type(i)==list:
            self.bag.extend(i) # append whole list i into bag with extend method
        else:
            self.bag.append(i) # append single item i into bag 

# example
Emptybag = Bag()
Bag1 = Bag('item1') # Initialize with 1 item
Bag2 = Bag(['item1', 'item2']) # initialize with list of items