【发布时间】: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