大脑一直在超载,我怎么能像Python一样这么做?

2024-05-23 15:50:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我不能在python中重载函数,而且我似乎无法用python来获得我所追求的行为。在

例如:

class Hop(object):
   def __init__(self, variety, aa, qty, time):
      self.variety = variety
      self.aa = aa
      self.qty = qty
      self.time = time

class HopBill(object):
   hop_list = []
   def add(self, hop):
      self.hop_list.append(hop)
   # Where I would put an overloaded function?
   def add(self, variety, aa, qty, time):
      self.hop_list.append(Hop(variety, aa, qty, time))

我并不是很喜欢使用kwds,只是添加一堆逻辑来解码我的函数接收到的输入。在

我觉得有一个更好的方法来设置这个,有人有什么建议,如何采取一个更Python的方法?在

谢谢!在


Tags: 方法函数selfaddobjecttimedeflist
3条回答

有一种方法:

class HopBill(object):
    def __init__(self):
        self.hop_list = []
    def add(self, hop_or_variety, aa=None, qty=None, time=None):
        if isinstance(hop_or_variety, Hop):
            assert aa is None, qty is None, time is None
            self.hop_list.append(hop_or_variety)
        else:
            self.hop_list.append(Hop(hop_or_variety, aa, qty, time))

还请注意,我在__init__中定义了hop_list,而不是类定义,否则所有HopBill将共享相同的hop_list。在

您可以在Spam类的方法中动态创建鸡蛋的实例。在

这应该能解决问题

def add(self, variety, aa, qty, time):
    new = Hop(variety, aa, qty, time)
    self.hop_list.append(new)

只需要两种方法。Init hop_-list-in-the-Init-Init\u或者hoppill的实例将共享该列表:

class HopBill(object):
   def __init__(self):
       self.hop_list = []
   def add(self, hop):
      self.hop_list.append(hop)
   def addnew(self, variety, aa, qty, time):
      hop = Hop(variety, aa, qty, time)
      self.add(hop)

相关问题 更多 >