python中如何定义类与对象_在python中创建用户定义类的对象集

table = set([])

class GlobeLearningTable(object):

def __init__(self,mac,port,dpid):

self.mac = mac

self.port = port

self.dpid = dpid

def add(self):

global table

if self not in table:

table.add(self)

class LearningSwitch(object):

def __init__ (self, connection, transparent):

self.connection = connection

self.transparent = transparent

self.macToPort = {}

connection.addListeners(self)

self.hold_down_expired = _flood_delay == 0

def _handle_PacketIn (self, event):

packet = event.parsed

self.macToPort[packet.src] = event.port # 1

packet_src = str(packet.src)

packet_mac = packet_src.upper()

entry = GlobeLearningTable(packet_mac, event.port, dpid_to_str(self.connection.dpid))

entry.add()

问题:entry.add()方法每次调用时都会添加新对象,并递增表中的项目.

这不应该发生,因为

>在add方法中,我正在检查表中是否有该对象,然后我添加该特定对象.

> Table是一个无序列表的集合,它不应该有重复的对象.

帮助:在这个设置中有什么办法我只能在不在表格中时添加对象.

解决方法:

您需要实现__eq__和__hash__方法来教授Python如何识别唯一的GlobeLearningTable实例.

class GlobeLearningTable(object):

def __init__(self,mac,port,dpid):

self.mac = mac

self.port = port

self.dpid = dpid

def __hash__(self):

return hash((self.mac, self.port, self.dpid))

def __eq__(self, other):

if not isinstance(other, type(self)): return NotImplemented

return self.mac == other.mac and self.port == other.port and self.dpid == other.dpid

现在您的对象具有可比性,并且相等的对象也将返回__hash__的相等值.这使set和dict对象可以有效地存储对象,并检测它是否已存在:

>>> demo = set([GlobeLearningTable('a', 10, 'b')])

>>> GlobeLearningTable('a', 10, 'b') in demo

True

标签:python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值