【问题标题】:Def return in class as second, third argument for ClassDef 在类中返回作为 Class 的第二、第三个参数
【发布时间】:2016-03-09 15:15:54
【问题描述】:

我正在创建一个类来进行一些计算。该课程将有 3 个参数开始。我在简化的表示中这样做了:

class TheCalcs:

    def __init__(self, pk_from_db, cat_score_list, final_score):
        self.pk_from_db = pk_from_db
        self.cat_score_list = cat_score_list
        self.final_score = final_score

    def calculate_cat_score(self):
        #Do some calcs with the data of the pk_from_db and return that!
        a_list_of_scores = []  # create a list of scores 
        return a_list_of_scores

    def final_score(self): # The argument for this function would be the return of the calculate_cat_score function! 
        # Again do some calcs and return the final score 
        the_final_score = int()
        return the_final_score

    def score_grade(self): # the argument this this function again the return but now from the final_score function
        # Do some cals and return the grade
        the_grade = ("a string", "an integer")
        return the_grade

当我调用类时,我必须提供参数 --> 但是,正如你所看到的,我现在只处理第一个参数的值。第二个和第三个在整个班级中计算。当我只用一个参数调用类时,我当然会遇到参数失败的错误。有人对此有想法吗?

【问题讨论】:

  • 那为什么还要传入这些参数呢?
  • 如果在初始化时不知道这些属性的值,为什么要在初始化时提供这些属性?
  • 如何让它们成为可选的或者只是初始化self.cat_score_list = None

标签: python python-2.7 class


【解决方案1】:

如果这些值是计算出来的,就不要将它们作为参数。您可以改为调用这些计算方法来计算值:

class TheCalcs:
    def __init__(self, pk_from_db):
        self.pk_from_db = pk_from_db
        self.cat_score_list = self.calculate_cat_score()
        self.final_score = self.calculate_final_score()

    # ...

或推迟计算,直到您需要它们。

【讨论】:

  • 像这样我在 init 函数中调用第二个和第三个函数对吗?这也是编程经验的不足。我将不得不看看这是如何“工作”的,但现在它似乎很有帮助!
  • @GuidoPeters:完全正确。没有规定__init__ 中设置的属性值必须来自参数。您可以设置任何您喜欢的属性,这些属性的值可以来自任何表达式,包括对刚刚创建的新实例的方法调用。
  • 我不得不玩一会儿才能让它开始!但是python控制台万岁!我一切顺利!
猜你喜欢
  • 2021-08-23
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多