如何将一个函数的结果存储到一个类中?

所以我创建了两个类。第一个(myModel)有一个函数,可以用“predictFinalIncome”函数计算收入。我出于 SO 的目的对其进行了简化。


class myModel:

  """

  The earning growth model for individuals in the utopia 

  """

  def __init__(self, bias) :

    """

    :param bias: we will use this potential bias to explore different scenarios to the functions of gender and ethnicity


    :param b_0: the intercept of the model.\ 


    :param b_age: age at world creation


    :param b_education: similar. 


    :param b_gender: similar


    :param b_marital: marital status


    :param b_ethnic: similar


    :param b_industry: similar


    :param b_income: similar.

    """


    self.bias = bias # bias is a dictionary with info to set bias on the gender function and the ethnic function


  def predictFinalIncome( self, n, person ): 

    for i in range(n):

      n_income = n_income* i

    return n_income

所以这个类接受一个“Person”字典,比如:


utopModel = myModel( { "gender": False, "ethnic": False } ) 

months = 12

plato = { "age": 58, "education": 20, "gender": 1, "marital": 0, "ethnic": 2, "industry": 7, "income": 100000 }

utopModel.predictFinalIncome(months,plato)

所以我的目标是创建一个类(Person),它可以在每次调用该函数时存储给定 Person 的 predictFinalIncome(),从而删除前一个。这样我就可以跟踪一个人并在我调用该函数时存储他们的预测收入。


我想将其作为收入存储在 Person 中。


class Person:

  """

  The attributes of a Person to build a person up, having their information in one place as it changes.

  """

  def __init__(self, bias) :

    """

    :param age: person's age


    :param education: person's years of education 


    :param gender: male or female


    :param marital: marital status


    :param ethnic: ethnicity


    :param industry: what sector of work


    :param income: salary

    """

  def age00(self, age):

    return age


  def age(self, age):

    return 


  def income00(self, income):

    return income


  def income(self, n, income):

    return 


  def __getitem__(self, item):

    return self.__dict__[item]


心有法竹
浏览 133回答 2
2回答

交互式爱情

我认为这里有两种解决方案:你predictFinalIncome在里面写Person。当您调用predictFinalIncome方法时,您会将收入值保存为Person类的属性您将Person实例作为predictFinalIncome方法的参数传递。在计算收入后,您可以使用该实例进行储蓄。见下文def predictFinalIncome( self, n, specificPerson: Person ):     for i in range(n):      n_income = n_income* i    # new lines    specificPerson.income += n_income #income updated    specificPerson.age = ((specificPerson.age*12) + n)/12 # age updated当你predictFinalIncome在外面打电话时:utopModel = myModel( { "gender": False, "ethnic": False } ) months = 12specificPerson = Person(..something here..)utopModel.predictFinalIncome(months,specificPerson)现在,当您调用方法时,您的specificPerson实例会自动更新收入predictFinalIncome

holdtom

所以 NimaNr 的解决方案(在您的评论中)可能是最简单的解决方案。如果您将 predictFinalIncome() 保留在 myModel 类中,您将需要为您的 Person 的收入变量创建一个setter函数。它看起来像这样:def setIncome(self, x):     self.Income = x你想要在你的predictFinalIncome方法中做的是用你得到的 n_income 值调用我们刚刚在上面创建的设置器。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python