【问题标题】:How to declare the __init__ variables that is not necessarily required如何声明不一定需要的 __init__ 变量
【发布时间】:2018-02-01 04:15:58
【问题描述】:
class Gathering(object):

    def __init__(self, date, spent1, spent2, spent3, spent4):
        """Return a gathering object whose date is declared """
        self.date = date
        self.spent1 = spent1
        self.spent2 = spent2
        self.spent3 = spent3
        self.spent4 = spent4
        self.spent_total = spent1+spent2+spent3+spent4

    def per_person(self):
        return self.spent_total/3

我写了一个简短的脚本,当我和我的朋友有一些东西时,我可以很容易地计算出一个人的部分。我们通常会搬家,花的钱不一样,但那天晚上我们去了多少地方总是不一样的。

所以我想将spend1,2,3,4 变量设为不一定需要,我该怎么做?

【问题讨论】:

  • def __init__(self, date, spend1=0, spend2=0, spend3=0, spend4=0)
  • @Gang 这就是精神 thx
  • @Gang 让它更健壮,有什么办法可以自动拉长那些spend_n 部分?像直到花费 1000 也是可能的。
  • d = {} , 将某事添加到 dict, Gathering(**d)
  • **双星号指的是什么?我知道一个星号,但不知道其中两个

标签: python class init


【解决方案1】:

您可以使用可变数量的参数:

class Gathering(object):
    def __init__(self, date, *args):
        """Return a gathering object whose date is declared """
        self.date = date
        self.spent = args
        self.spent_total = sum(args, 0)

    def per_person(self):
        return self.spent_total / 3.0

sent 包含一个值元组。您可以像这样使用您的课程:

g1 = Gathering(date1, 1, 2, 3)
g2 = Gathering(date2, 2, 3)

等等。

【讨论】:

  • 谢谢你,现在我和我的朋友可以去任何我们想去的酒吧。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 2015-03-25
  • 2011-08-16
  • 1970-01-01
相关资源
最近更新 更多