类:如何使用户可以在我的类中输入字典?

时间:2021-10-29 20:13:16

I need to edit my code so rather than creating the bag dictionary myself below, instead the user can input their own dictionary. A doc test of this would go as:

我需要编辑我的代码,而不是在下面自己创建包字典,而是用户可以输入自己的字典。对此的文档测试将如下:

>>> bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1})
>>> bag.draw()
'yellow'
>>> bag.replace('yellow')

The user would be inputting the dictionary into their call and I would no longer need "bag".

用户将字典输入到他们的通话中,我将不再需要“包”。

Also I randomly keep getting

我也随机继续前进

TypeError: 'int' object is not subscriptable 

or

TypeError: 'int' object is not iterable

every now and then when I try running this code.

我不时地尝试运行此代码。

The doc test that I am personally running just for looking over my work is:

我个人为了查看我的工作而进行的文档测试是:

>>>bag = BeadBag()
>>>bag.draw()
'black'
>>>bag.replace('yellow')
{'red': [11], 'yellow': 23, 'green': [33], 'blue': [44], 'white': [55], 'black': 65}

But it's not quite what I need it to be.

但这并不是我需要的。

import random
class BeadBag(object):
    """
    >>> bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1})
    >>> bag.draw()
    'yellow'
    >>> bag.replace('yellow')
    >>>
    """
    bag = {'red':[11], 'yellow':[22], 'green':[33], 'blue':[44], 'white':[55], 'black':[66]}

    def draw(self):

        words = []
        for i in BeadBag.bag.keys():
            words.append(i)
        rand = random.choice(words)
        minus = ((BeadBag.bag.get(rand))[0]-1) #subtracts one from each draw
        for key, value in BeadBag.bag.items():
            BeadBag.bag[rand] = minus
        return rand

    def replace(self, color):
        cvalue = (BeadBag.bag[color])
        for i in cvalue:
            val = int(i)
        add = val+1
        for key, value in BeadBag.bag.items():
            BeadBag.bag[color] = add
        return BeadBag.bag

4 个解决方案

#1


0  

When defining your class, you need to provide an __init__ function. This will take arguments that are the items provided to the class when you create it.

定义类时,需要提供__init__函数。这将获取在创建类时提供给类的参数。

class BeadBag():
    def __init__(self, input_dictionary):
        self.bag = input_dictionary

#2


0  

First you need to use self to denote your class instead of BeadBag inside your class.

首先,您需要使用self来表示您的班级而不是班级中的BeadBag。

start from here.

从这里开始。

import random


class BeadBag(object):
    def __init__(self, d):
        self.d = d
        self.words = d.keys()

    def draw(self):
        rand = random.choice(self.words)
        #self.d will be your dict. do whatever you want.

    def replace(self, color):
        cvalue = self.d[color]
        # rest of the code.

#3


0  

If I understood correctly what you want to accomplish with your class, this may do it:

如果我理解你想要在课堂上完成什么,可以这样做:

import random


class BeadBag(object):
    """
    >>> bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1})
    >>> bag.draw()
    'yellow'
    >>> bag.replace('yellow')
    >>>
    """

    def __init__(self, d):
        self.bag = d

    def draw(self):
        rand = random.choice([k for k in self.bag.keys()])
        minus = self.bag.get(rand) - 1
        self.bag[rand] = minus

        return rand

    def replace(self, color):
        self.bag[color] += 1

sample usage:

>>> bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1})
>>> bag.draw()
'red'
>>> bag.bag
{'green': 44, 'blue': 20, 'yellow': 15, 'red': 10, 'white': 2, 'black': 1}
>>> bag.replace('red')
>>> bag.bag
{'green': 44, 'blue': 20, 'yellow': 15, 'red': 11, 'white': 2, 'black': 1}

I assumed you meant to store the bag dictionary on an instance attribute rather than a class one (which is shared with all instances).

我假设您打算将bag字典存储在实例属性而不是第一类(与所有实例共享)。

The draw method decrements 1 from a random key in bag and returns the decremented key.

draw方法从bag中的随机密钥递减1并返回递减的密钥。

The replace method simply increments 1 from the bag[color].

替换方法只是从包[颜色]增加1。

#4


0  

Here's how to the dictionary to be specified when instance of the BeadBag class are created and each one will have it's own bag dictionary attribute.

下面是如何在创建BeadBag类的实例时指定字典,并且每个实例都有自己的包字典属性。

This still doesn't pass the doctest, but that because there are issues in both the draw) and replace() methods that have nothing to do with the question you've asked — and it's unclear to me exactly what you were trying to do in them, so they still need fixing.

这仍然没有通过doctest,但是因为draw和)方法都存在问题,这些问题与你提出的问题无关 - 而且我不清楚你到底想要做什么在他们中间,所以他们仍然需要修理。

import ast
import doctest
import random

class BeadBag(object):
    """
    >>> bag = BeadBag("{'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1}")
    >>> bag.draw()
    'yellow'
    >>> bag.replace('yellow')
    >>>
    """

    def __init__(self, string):
        self.bag = ast.literal_eval(string)
        assert isinstance(self.bag, dict)

    def draw(self):
        words = []
        for i in self.bag.keys():
            words.append(i)
        rand = random.choice(words)
        minus = ((self.bag.get(rand))[0]-1) #subtracts one from each draw
        for key, value in self.bag.items():
            self.bag[rand] = minus
        return rand

    def replace(self, color):
        cvalue = (self.bag[color])
        for i in cvalue:
            val = int(i)
        add = val+1
        for key, value in self.bag.items():
            self.bag[color] = add
        return self.bag

if __name__ == '__main__':
    doctest.testmod()

#1


0  

When defining your class, you need to provide an __init__ function. This will take arguments that are the items provided to the class when you create it.

定义类时,需要提供__init__函数。这将获取在创建类时提供给类的参数。

class BeadBag():
    def __init__(self, input_dictionary):
        self.bag = input_dictionary

#2


0  

First you need to use self to denote your class instead of BeadBag inside your class.

首先,您需要使用self来表示您的班级而不是班级中的BeadBag。

start from here.

从这里开始。

import random


class BeadBag(object):
    def __init__(self, d):
        self.d = d
        self.words = d.keys()

    def draw(self):
        rand = random.choice(self.words)
        #self.d will be your dict. do whatever you want.

    def replace(self, color):
        cvalue = self.d[color]
        # rest of the code.

#3


0  

If I understood correctly what you want to accomplish with your class, this may do it:

如果我理解你想要在课堂上完成什么,可以这样做:

import random


class BeadBag(object):
    """
    >>> bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1})
    >>> bag.draw()
    'yellow'
    >>> bag.replace('yellow')
    >>>
    """

    def __init__(self, d):
        self.bag = d

    def draw(self):
        rand = random.choice([k for k in self.bag.keys()])
        minus = self.bag.get(rand) - 1
        self.bag[rand] = minus

        return rand

    def replace(self, color):
        self.bag[color] += 1

sample usage:

>>> bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1})
>>> bag.draw()
'red'
>>> bag.bag
{'green': 44, 'blue': 20, 'yellow': 15, 'red': 10, 'white': 2, 'black': 1}
>>> bag.replace('red')
>>> bag.bag
{'green': 44, 'blue': 20, 'yellow': 15, 'red': 11, 'white': 2, 'black': 1}

I assumed you meant to store the bag dictionary on an instance attribute rather than a class one (which is shared with all instances).

我假设您打算将bag字典存储在实例属性而不是第一类(与所有实例共享)。

The draw method decrements 1 from a random key in bag and returns the decremented key.

draw方法从bag中的随机密钥递减1并返回递减的密钥。

The replace method simply increments 1 from the bag[color].

替换方法只是从包[颜色]增加1。

#4


0  

Here's how to the dictionary to be specified when instance of the BeadBag class are created and each one will have it's own bag dictionary attribute.

下面是如何在创建BeadBag类的实例时指定字典,并且每个实例都有自己的包字典属性。

This still doesn't pass the doctest, but that because there are issues in both the draw) and replace() methods that have nothing to do with the question you've asked — and it's unclear to me exactly what you were trying to do in them, so they still need fixing.

这仍然没有通过doctest,但是因为draw和)方法都存在问题,这些问题与你提出的问题无关 - 而且我不清楚你到底想要做什么在他们中间,所以他们仍然需要修理。

import ast
import doctest
import random

class BeadBag(object):
    """
    >>> bag = BeadBag("{'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1}")
    >>> bag.draw()
    'yellow'
    >>> bag.replace('yellow')
    >>>
    """

    def __init__(self, string):
        self.bag = ast.literal_eval(string)
        assert isinstance(self.bag, dict)

    def draw(self):
        words = []
        for i in self.bag.keys():
            words.append(i)
        rand = random.choice(words)
        minus = ((self.bag.get(rand))[0]-1) #subtracts one from each draw
        for key, value in self.bag.items():
            self.bag[rand] = minus
        return rand

    def replace(self, color):
        cvalue = (self.bag[color])
        for i in cvalue:
            val = int(i)
        add = val+1
        for key, value in self.bag.items():
            self.bag[color] = add
        return self.bag

if __name__ == '__main__':
    doctest.testmod()