繁体   English   中英

如何创建__init__函数?

[英]How to create the __init__ function?

这是说明:

1.在名为bag.py的模块中定义一个名为Bag的类

2.定义一个具有一个参数的init方法,该参数是可迭代的值,这些值会初始化袋子。 Writing Bag()构造一个空袋子。 编写Bag(['d','a','b','d','c','b','d'])构造一个包含一个'a',两个'b',一个'c'的袋子,以及三个“ d”。 Bag类中的对象应仅存储上面指定的字典:不应存储/操纵任何其他自变量

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

我不知道如何使init函数。 因为第一个输入调用b = Bag(),所以将始终引发错误:b = Bag()引发异常TypeError: init ()缺少1个必需的位置参数。 谁能告诉我如何解决?

第一个引发的异常:

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

第二个例外:

如果您实际上通过Bag构造函数传递了一个参数,则该长度将大于0,并且将永远不会创建 bag,因此无法对其进行追加。 我不确定您要做什么,但也许self.bag = []而不管i的长度如何?

您的init方法期望参数i被初始化,而您的代码的另一个问题是self.bag不会在len(i)不为零的情况下初始化为列表,如果未将其定义为list,则不能追加到bag在手。 以下代码应符合您的要求

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

如果使用collections模块中的内置Counter类,听起来事情可能会更简单。 从文档:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM