简体   繁体   English

构建python字典类

[英]building python dictionary class

I'm trying to write a hashing class where you can add and see if the item exists using Python's built-in dictionary. 我正在尝试编写一个哈希类,您可以在其中添加并使用Python的内置字典查看该项目是否存在。 I tried this but seems to ignore the put method, but it is possible to check for existing item. 我尝试了此操作,但似乎忽略了put方法,但是可以检查现有项。 Can anyone help me? 谁能帮我?

class Hashtable (object):
    def __init__(self):
        atom={}
        self.atom=atom

    def put(self ,name ,number):
        atom={}
        self.atom=atom
        self.name=name
        self.number=number
        self.atom[self.name]= self.number

    def get(self ,name):
        return self.atom[name]

    def __str__ (self):
        keysstring =str(self.atom[self.name])
        return keysstring

In your put method, you assign a new empty dictionary to self.atom , erasing whatever was already stored there. put方法中,您将一个新的空字典分配给self.atom ,删除那里已经存储的任何东西。 Just do this: 只要这样做:

def put(self, name, number):
    self.atom[name] = number

There's no need to assign name and number to self.name and self.number , since they will also be overwritten every time you call put . 无需为self.nameself.number分配namenumber ,因为每次您调用put时它们也会被覆盖。

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

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