如何创建__init__函数?

问题描述:

这是操作的指令:如何创建__init__函数?

1.定义一个模块中名为袋类名为bag.py

2.Define一个INIT方法具有一个参数,即initalize袋值的迭代。书写袋()构成一个空袋子。书包(['d','a','b','d','c','b','d'])构成一个'a',两个'b','c' ,还有三个'd'。在袋类对象应该只存储字典上述规定的:它不应该存储/处理任何其他自变量

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() 

这是我得到的错误:

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 

输入是:

# 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 

我不知道如何使初始化功能。因为第一个输入调用b = Bag(),所以总是会引发错误:b = Bag()引发异常TypeError:init()缺少1个需要的位置参数。任何人都可以告诉我如何解决它?

你的init方法期望我的参数被初始化, 而你的代码的另一个问题是self.bag将永远不会初始化为一个列表,如果len(i)不为零,你可以将它追加到bag if它并未事先将其定义为清单。下面 代码应该适合你想要什么

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 
+0

谢谢,它工作正常。 – jiahuiding

第一个出现的异常:

c-->b = Bag()调用需要传递给包的参数。例如Bag(['f', 'o', 'o'])

第二个出现的异常:

如果你确实穿过袋构造函数的参数长度将大于0和包永远不会创建所以你不能追加到它。我不知道你想要做什么,但不管我的长度如何,也许self.bag = []

+0

我只是不知道如何使它工作。由于c_> b = Bag()将在__init__函数中存在参数'i'时始终导致错误。但是指令要求我用该参数'i'创建__init__函数。 – jiahuiding

+0

我很抱歉,我仍然不完全明白你在问什么。你可以尝试将'def __init __(self,i):'改成'def __init __(self,i = []):' – atomSmasher

听起来像是如果你使用的东西,可能是简单的内置Counter类,这是collections模块中。从文档:

>>> c = Counter()       # a new, empty counter 
>>> c = Counter('gallahad')     # a new counter from an iterable 
>>> c = Counter({'red': 4, 'blue': 2})  # a new counter from a mapping 
>>> c = Counter(cats=4, dogs=8)    # a new counter from keyword args