简体   繁体   English

class 方法如何成为替代构造函数,因为它们只返回我们的对象? 在 python

[英]How class methods can be alternative constructors as they just return us objects? in python

The purpose of constructors is to initialize the state of the object.构造函数的目的是初始化 object 的 state。 init in python much behaves like a constructor in python as it initialize the state of the objects. python 中的init很像 python 中的构造函数,因为它初始化对象的 state。 But I read that classmethods are also used as alternative constructors.但我读到 classmethods 也被用作替代构造函数。 How?如何? I am not getting this point.我不明白这一点。 How classmethods acts as constructors?类方法如何充当构造函数? See the code below:请看下面的代码:

class ABC:
   def __init___(self,name)
       self.name=name
   @classmethod
   def from_string(cls,name):
       return cls(name)     # Here classmethod "from_string"  just returns me an object.So 
                            # How can we say that this class method act as constructor? as it
                            # just gives me an object. And the purpose of constructor is not
                            # create an object but to initialize the state of object. Please
                            # clarify this confusion. Thanks
                              

What is meant by "alternative constructor" is best illustrated:最好地说明“替代构造函数”的含义:

>>> from datetime import datetime
>>> datetime(2020, 1, 1)
datetime.datetime(2020, 1, 1, 0, 0)
>>> datetime.now()
datetime.datetime(2022, 9, 1, 14, 50, 43, 536862)

You can either instantiate the class with datetime(...) and pass it the required arguments, or you use datetime.now() which also simply gives you an instance of the datetime class, but fills in the values with the current time.您可以使用datetime(...)实例化 class 并将所需的 arguments 传递给它,或者您使用datetime.now()也可以简单地为您提供datetime class 的实例,但用当前时间填充值。 It's an alternative way to construct/instantiate the class with different functionality than the main constructor has.这是构造/实例化class 的另一种方法,其功能与主构造函数不同。

Not all languages make a distinction between construction and initialization.并非所有语言都区分构造和初始化。 Python does. Python 可以。 __new__ creates an object (usually, by delegating to an inherited __new__ ; object.__new__ is the only way to really create a new object) or returns an existing object. __new__创建一个 object (通常,通过委托给继承的__new__object.__new__真正创建新对象的唯一方法)或返回现有的 ZA8CFDE6331BD59EB2AC96F8911C4B66。 __init__ receives that object as an argument to further initialize it. __init__接收object 作为参数以进一步初始化它。 (Whether __init__ gets called depends on whether cls.__new__ returns an instance of cls ; it isn't required to, but usually does.) (是否调用__init__取决于cls.__new__是否返回cls的实例;这不是必需的,但通常会这样做。)

A class method is used to implement an alternate constructor because it can behave much like __new__ . class 方法用于实现备用构造函数,因为它的行为很像__new__ It receives the class and some other arguments, and in this scenario returns an object, usually by calling the __new__ method (indirectly, by calling the class) with arguments derived from its own. It receives the class and some other arguments, and in this scenario returns an object, usually by calling the __new__ method (indirectly, by calling the class) with arguments derived from its own.

Here's a simple example:这是一个简单的例子:

class A:
    # trivial constructor: it just defers to super().__new__
    # You could leave this undefined.
    def __new__(cls, a):
        return super().__new__(cls)

    def __init__(self, a):
        self.a = a

    @classmethod
    def from_pair(cls, x, y):
        return cls(x + y)

a1 = A(6)
a2 = A.from_pair(2, 4)

Both a1 and a2 produce instances of A whose a attribute is 6 . a1a2都生成A的实例,其a属性为6 The from_pair class method acts as an alternate constructor in that it creates an instance of A , but hides the details of how the two arguments are used to do so. from_pair class 方法充当替代构造函数,因为它创建A的实例,但隐藏了如何使用两个 arguments 的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Python 中的方法返回对象? - How to return objects from methods in Python? Python中的替代构造函数 - Alternative Constructors in Python 如何在Python类描述符对象上调用方法? - How to call methods on Python class descriptor objects? 如何使用 pytest 模拟返回另一个 class 对象的 class 方法? - How to mock a class methods that return another class objects with pytest? 使用类方法实现替代构造函数,如何向这些替代构造函数添加函数? - Using classmethods to implement alternative constructors, how can I add functions to those alternative constructors? 如何在 Python3 中使用构造函数模拟对象? - How to mock objects with constructors in Python3? 子类方法能否返回与 python 中的抽象 class 不同的类型? - Can subclass methods return a different type than the abstract class in python? 派生类构造函数如何在python中工作? - How do derived class constructors work in python? 如何在Python中区分类方法和静态方法并返回布尔值 - How to distinguish between class and static methods in Python and return a Boolean 如何在Python中处理具有不同参数集(或类型)的构造函数或方法? - How to handle constructors or methods with a different set (or type) of arguments in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM