繁体   English   中英

在python中构造一个class而不直接调用构造函数

[英]Constructing a class in python without directly calling the constructor

在 python 中,如果我们定义一个名为 Start 的 class 并使用如下所示的参数对其进行初始化...

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

Once defined, and after importing Start into another python file is there any way to make a function or attribute inside the class so I can construct the class directly like this?

# Start.make or Start.make()
# Sample usage below
s = Start.make #initializes Start with the argument of 1

我要做的是让 Start.make 完成与Start(1)相同的目标,因此我可以潜在地创建其他构造常用值的方法,而无需手动将 arguments 放入Start()构造函数中。 这在 Python 中是否可能? 如果没有,我可以遵循任何替代解决方案来达到类似的结果吗?

使用 static 方法:

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

    @staticmethod
    def make():
        return Start(1)

s = Start.make()

您可以使用 static 方法,也可以使用 class 方法:

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

    @classmethod
    def make(cls):
        return cls(1)

要创建实例,请使用以下命令:

>>> s = Start.make()
>>> s.a
1

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM