【问题标题】:Why is return included in the alternative constructor?为什么 return 包含在替代构造函数中?
【发布时间】:2021-12-30 17:28:09
【问题描述】:
class Student:
    def __init__(self, first, last):
        self.first = first
        self.last = last

    @classmethod    
    def from_string(cls, emp_str):
        first, last = emp_str.split("-")
        return cls(first, last)

Student_1 = Student("Cool", "Person")

Student_2 = "Another-One"

Student_2 = Student.from_string(Student_2)

为什么在这个类方法中使用return?我知道你需要它来工作。但是我无法理解为什么需要包含它。据我所知——在这个类方法的例子中,cls(first, last)__init__(self, first, last) 做同样的事情。但是为什么需要在其中包含return 呢?不应该只是cls(first, last) 就足以调用__init__,这是您在构造Student_1 之类的实例时已经做的吗?

你能解释一下我的困惑在哪里吗?

【问题讨论】:

  • 请注意,__init__ 不是构造函数。它是已构造对象的初始化器。

标签: python oop constructor class-method


【解决方案1】:

不应该只是cls(first, last) 就足以调用__init__,这是您在构造像Student_1 这样的实例时已经做的吗?

是的,像这样调用构造函数将导致在cls 的新实例上调用__init__。但是,如果没有 return,新实例将被丢弃from_string() 方法不会返回任何内容。

如果将其设为全局函数而不是类方法可能会更清楚。你能看出这两个函数之间的区别以及为什么第一个不起作用吗?

class Student:
    ...


def student_from_string(emp_str):
    first, last = emp_str.split("-")
    Student(first, last)

student_from_string("A-B")  # None


def student_from_string(emp_str):
    first, last = emp_str.split("-")
    return Student(first, last)

student_from_string("A-B")  # Student("A", "B")

为什么在__init__不需要 return?因为您没有调用student = [new student].__init__(...),所以您使用的是student = Student(...)__init__ 是一种特殊的初始化方法,预计不会返回任何内容。您很少显式调用它(super() 除外),但它会在正常的构造函数调用期间自动调用。

另请参阅:https://stackoverflow.com/a/674369/23649

【讨论】:

    【解决方案2】:

    您注意到from_string 是一个类方法(不是实例方法)。 在行Student_2 = Student.from_string(Student_2)

    当你调用 from_string 时,它被分配给另一个变量。 (您分配给同一个 Student_2 )

    如果没有返回,这个分配将不会发生(不会返回那里。)

    [注意,cls函数返回一个对象实例]

    __instance__from_string 在这里没有做同样的事情。 在 instance 中,您将值分配给实例属性。 但是from_string,你又调用了构造函数,给实例属性赋值。

    【讨论】:

      猜你喜欢
      • 2015-06-12
      • 2016-03-27
      • 2014-02-09
      • 2016-07-17
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多